Router DIY — router.navigate

Ran Wahle
2 min readMay 5, 2019

--

After we’ve managed to alter our anchor element behavior and have it call our own implementation, it is time to really implement it.

What should we do?

  1. Change part of the application (i.e — show another screen of it)
  2. Manually change the address displayed on our browser’s address bar.

Router & Router outlet

Not long ago, I’ve developed using angular, in my implementation I have chosen the terminology used by the Angular team, to have a component called “Router Outlet” that should present a component, according to the app’s new url. For now, let’s just have one router outlet on the document, and get it by a simple querySelector

get routerOutlet() {
return document.querySelector('router-outlet');
}

We do it by merely setting an attribute on out Router outlet component, and letting it do the rest.
Before doing so, we need to validate the url being sent to us, and throw an exception in case it is not valid.

try {
url = url === '/' ? url : new URL(url).pathname;
} catch (err) {
throw Error(`Cannot construct url from ${url}`)
}


this.routerOutlet.setAttribute('current-url', url);

On the other hand, we should have the new url written on the address bar. TO do that, we will use the history API using history.pushState

history.pushState(null, null, url);

So, the navigate method should look like that:

navigate(url) {
try {
url = url === '/' ? url : new URL(url).pathname;
} catch (err) {
throw Error(`Cannot construct url from ${url}`)
}

history.pushState(null, null, url);

this.routerOutlet.setAttribute('current-url', url);
}

Next, we will go to the router-outlet itself.

--

--