Originally published on Javascript by doin

Single page applications are everywhere around us, React-based, Vue or in vanillaJS. To have a good single page application you need to have a fantastic router mechanism.

Library like navigo or react-router are really great. But how do they work? Do we really need to import the entire library? Or is it ok to just use a 10% of it? In general, creating a fast and useful router is very simple and requires little less than 100 lines of code.

Requirements

Our router should be

Let’s start to code

Generally only one instance of router is used for each webapp but there are many cases where it is necessary to have more than one, for this we will not implement a Singleton pattern. Our router need 4 basic properties to work:

class Router {
  routes = [];
  mode = null;
  root = "/";

  constructor(options) {
    this.mode = window.history.pushState ? "history" : "hash";
    if (options.mode) this.mode = options.mode;
    if (options.root) this.root = options.root;
  }
}

export default Router;

Adding and removing routes

Adding or delete a route will just push or delete an element from an array

class Router {
  routes = [];
  mode = null;
  root = "/";

  constructor(options) {
    this.mode = window.history.pushState ? "history" : "hash";
    if (options.mode) this.mode = options.mode;
    if (options.root) this.root = options.root;
  }

  add = (path, cb) => {
    this.routes.push({ path, cb });
    return this;
  };

  remove = path => {
    for (let i = 0; i < this.routes.length; i += 1) {
      if (this.routes[i].path === path) {
        this.routes.slice(i, 1);
        return this;
      }
    }
    return this;
  };

  flush = () => {
    this.routes = [];
    return this;
  };
}

export default Router;

Get the current path

We obviously need to know where we are in a specific moment in our application.