DEV Community

How to build a Router with vanilla JavaScript

Victor Mbamara 🇳🇬 on May 16, 2019

So many times, we might want to write our JavaScript code in a single file but we want the code to be executed only if a particular route is matche...
Collapse
 
vijayjangid profile image
Vijay Jangid

Nicely done.

$0.02 from me take it or leave it.

constructor(){
  this.routes = [];
  return this; // I don't think this is explicitly required 
                     // (unless you want to return something else than 'this')
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kodnificent profile image
Victor Mbamara 🇳🇬

Very true Vijay, It'll only be required if i wanted to chain methods. I'll edit accordingly. Thanks for noting that.

Collapse
 
couch3ater profile image
Connor Tangney • Edited

Super informative and well written. One small thing that jumps out at me is that you mention you are using ES6 classes but make no mention of the other ES6 features you are using.

The example that jumps out at me:

You also noticed

let req = { path }

which also means

let req = { path: path }

This is a great example of shorthand properties, and making note of this may or may not be beneficial for newcomers.

Outside of that, this was an excellent first post! All these awesome first posts are making me really want to get my own up here now...

Kudos!

Collapse
 
kodnificent profile image
Victor Mbamara 🇳🇬

Thanks alot. You're right about making no mention of other ES6 features. I'll edit the post and generalize the use of es6 features rather than specifying just es6 classes.

Collapse
 
routersip profile image
routersip

Aside from the Web interface, you can likewise utilize the free downloadable Netgear Genie application for the activity network ip address: 192.168.0.254

Collapse
 
itachiuchiha profile image
Itachi Uchiha

Nice :)

Maybe you can add a hash change event or something like that.

But I loved :)

Thanks.

Collapse
 
kodnificent profile image
Victor Mbamara 🇳🇬

Very true, Ali. But i just tried keeping it simple.

Collapse
 
vbpupil profile image
Dean Haines

Enjoyed the article, interesting read, thanks.

Collapse
 
mmucino1 profile image
Marco Muciño

I can't make it to work. Any route I navigate send me to a Not Found (404) page. What am I missing? Thanks.

Collapse
 
kodnificent profile image
Victor Mbamara 🇳🇬

This is because you need to setup a router from the serverside that routes all request to the server to a single page. Then take over the routing with javascript.

Collapse
 
jmz12 profile image
Jorge Méndez Ortega

very good entry, but I have a doubt the code runs in the front end