Router DIY — Let the magic begin

Ran Wahle
2 min readApr 28, 2019

--

After established that routing can be done, Let’s talk about the so called “magic” we need to pull off. The whole “magic” here is a function we need to call when routing begins. This function needs to be called both when the user takes action on our app (i.e — pressing a link), or when navigation event occurs (i.e a back-forward button is pressed, or the address changes on the address bar.

In here, let’s talk about pressing a link.

When the user presses a link button, we need to take three actions:

  1. Execute our own function
  2. Prevent browser’s default behavior
  3. Navigate ourselves

To do so, we need to have our own link component, we can extend the behaviour of an HTMLAnchorElement (‘a’ tag) (as in an angular <a [routerLink]/> element) or, have our own custom link (as in React <Link />element)

In fact, both approaches are good, let’s take the first one and extend the HTMLAnchorElement.

Assuming we have implemented the router elsewhere (and we should), let’s just import it, on the element extending HTMLAnchorElement, let’s alter its onclick behavior, so the class will look as follows

Now, let’s define our self routing anchor, using customElements API.

And use it

So, up until now, we have managed to get our own link element, and alter it’s default behavior, meaning that whenever we add the ‘self-routing-anchor’ attribute on an anchor element, our behavior will take place instead of the default one, however, we haven’t navigated anywhere. OK, let’s start doing that.

--

--