This content originally appeared on Bits and Pieces - Medium and was authored by Akshay Shinde
How to create a router in JavaScript when you’re not using a library or framework
Have you ever tried creating a Single Page Application (SPA) without using a library or framework such as React or Vue? If so, have you ever wondered how to create a router? Well, today we’re going to find out!
Before we start, you might want to read the following resources:
But don’t worry if you’re not sure what these mean, as we’ll cover them later.
Let’s begin!
Creating the web server
One thing we will need to demonstrate this is a web server. For this, we will be using Express. So let’s create a folder, initialize it with npm, then install Express:
mkdir vanillajs-router
cd vanillajs-router
npm init -y
npm install express
Note: If you’re not sure what npm is, I would suggest researching this and then coming back. We won’t be explaining the Express code, so please also take a moment to research that if you require it.
Now let’s create a server.js file which will be responsible for loading up our server:
const express = require('express');
const app = express();app.get('/*', (req, res) => {
res.sendFile(__dirname+"/index.html");
})app.listen(process.env.PORT || 3000, () => console.log("server is now running."));Now let’s run our server:
node server.js
If it loaded successfully, we should see “server is now running” in the terminal. Which means we can now visit the server at http://localhost:3000/.
The following is the body of a basic HTML template that we will be using. It has basic navigation links(non-hashed urls) and all of the content for a specific route will be shown inside of <div id="root”></div>:
<body>
<nav>
<ul>
<li><a href="/" onclick="router(event)">Home</a></li>
<li><a href="/about" onclick="router(event)">About</a></li>
<li><a href="/contact" onclick="router(event)">Contact</a></li>
<li><a href="/account" onclick="router(event)">Account</a></li>
</ul>
</nav>
<div id="root"></div>
<script src="/static/account.js" type="text/javascript"></script
<script src="/static/router.js" type="text/javascript"></script>
</body>
We will put all other static files (.css, .js) in a public folder. So go ahead and create that folder. You can download the index.css file for this project from here — although everything will still work without it. Put it into the public folder.
For serving static files from the public folder, add the following into server.js file. This static files will be served on ‘/static’ route:
app.use('/static', express.static('public'))Now we will add a routes array inside of router.js file. Create a file called router.js. path is the route and data is what we will show inside of <div id="root”></div>. We will add the following to router.js:
const routes = [
{ path: '/',
data: `<h1>Welcome to Home page.</h1><p>A home page is the main web page of a website. The term also refers to one or more pages always shown in a web browser when the application starts up.</p>`
},
{ path: '/about', data: `<h1>Welcome to About page.</h1> <p>The About page is the section of a website where people go to find out about the website they're on.</p>`
},
{ path: '/contact', data: `<h1>Welcome to Contact page.</h1> <p>A contact page is a common web page on a website for visitors to contact the organization or individual providing the website.</p>`
},
];
Then, we will create a function that will be triggered whenever a user clicks on any of the links in the navbar. Add the following to router.js:
const root = document.getElementById('root'); function router(event) {
event.preventDefault();
history.pushState({}, 'newUrl', event.target.href);
let route = routes.find(route => route.path == window.location.pathname);
root.innerHTML = route.data;
}If you visit http://localhost:3000/, and navigate to other links, you will see that the content of the page is changing.
Besides updating the content on the page, history.pushState() updates the URL in the browser. pushState() requires three parameters:
- State object for the route
- Title for the url
- URL
By doing this, we are adding a URL (eg. http://localhost:3000/about) to the stack of the history object, which is in the window of the browser.
However, if you try to move back and forth using the back/forward button, the content of the page will not update. This is because when we hit back/forward, a popstate event is fired which changes the active history. We can handle this adding the below code to router.js, and update the contents of the route according to it:
window.addEventListener('popstate', function() {
let data = routes.find(route => route.path == window.location.pathname);
root.innerHTML = data.data;
});But what about if you try to reload the site? We end up seeing nothing but the navbar. We can fix this by using the DOMContentLoaded event listener, and navigating to the correct page when the event is activated. We can do this by adding the following to router.js:
window.addEventListener('DOMContentLoaded', function() {
let route = routes.find(route => route.path == window.location.pathname);
root.innerHTML = route.data;
});And that’s it, you have a working router made using JavaScript.
You can find the GitHub repo for this project here. There’s also a live version hosted here. A big thanks to dcode for his blog. If you found this useful, be sure to share and let us know in the comments.
Build component-driven. It’s better, faster, and more scalable.
Forget about monolithic apps, start building component-driven software. Build better software from independent components and compose them into infinite features and apps.
OSS Tools like Bit offer a great developer experience for building component-driven. Start small and scale with many apps, design systems or even Micro Frontends. Give it a try →
How to Create a SPA Router with JavaScript was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Akshay Shinde
Akshay Shinde | Sciencx (2022-02-04T14:36:24+00:00) How to Create a SPA Router with JavaScript. Retrieved from https://www.scien.cx/2022/02/04/how-to-create-a-spa-router-with-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.