Yes, you read the title right, Client side router for a frameworkless SPA, that’s exactly what we are going to build in this story.
Before we dive into the code, let’s first understand what is client side routing.
This is how our router would render the page —
1. Listen on hashchange event or custom event in case of history.pushState().
2. When the URL changes, match and parse the URL to the route predefined in the code.
3. Look for the view to be rendered for that route, if no match is found render a 404 message.
**Enough theory, show me the code already!**
Below is the folder structure that we’d be working with
Let’s define a class to represent the Route in the router folder.
The Route class would take in 3 parameters while instantiating; name, path and the view associated to the route.
The setProps() method will set the props or properties that would be passed on to the route from the URL and the renderView() method would return the view of the route.
The Router class will be the heart of our routing system. It will take an array of route objects as the first parameter and the renderNode where the view will be injected as the second.