Build a very basic SPA JavaScript router
Tags: javascript, location, spa, router
Published: 2020-02-12 09:34:12

---
title: Build a very basic SPA JavaScript router
published: true
description: How to build a very basic SPA JavaScript router based on location.hash
tags: JavaScript, Location, SPA, Router
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/i20599m5m76hermrgnib.jpg
---

# Simple Plain JavaScript Router
In this post I'll implement an extreme basic SPA routing using plain JavaScript.
The goal is to give an idea of how it's possible to render different dynamic contents based on the URL with plan JavaScript.

## Requirements
We want to have a basic website that shows different topic based on 3 urls: 
 * http://localhost:3000/
 * http://localhost:3000/#/page1
 * http://localhost:3000/#/page2

For other urls we show an error message.
We can use HTML and plain JavaScript.

## Setup
Let's create the HTML page `index.html`:

```html
<html>
  <head>
    <title>JavaScript Router Example</title>
  </head>
  <body>
    <header>
      <h1>JavaScript Router Example</h1>
    </header>
    <section id="app"></section>
    <nav>
      <a href="/">Home</a> -
      <a href="#/page1">Page 1</a> -
      <a href="#/page2">Page 2</a>
    </nav>
    <script type="text/javascript" src="./app.js" />
  </body>
</html>
```

and an empty JS file `app.js`.

In order to serve it, we can install `live-server` globally:
```bash
npm install -g live-server
```

and then run it on our HTML file: 
```bash
live-server --port=3000 --entry-file=’./index.html’
```

Now it should be possibile to visit `http://localhost:3000/` and see the page.

## Create the components
Let's create the components now. 

We use the "template literal" expression, which is a string literal that can span multiple lines and interpolate expressions. 

Each component has a `render` method that returns the HTML template.
```javascript
// Components
const HomeComponent = {
  render: () => {
    return `
      <section>
        <h1>Home</h1>
        <p>This is just a test</p>
      </section>
    `;
  }
} 

const Page1Component = {
  render: () => {
    return `
      <section>
        <h1>Page 1</h1>
        <p>This is just a test</p>
      </section>
    `;
  }
} 

const Page2Component = {
  render: () => {
    return `
      <section>
        <h1>Page 2</h1>
        <p>This is just a test</p>
      </section>
    `;
  }
} 

const ErrorComponent = {
  render: () => {
    return `
      <section>
        <h1>Error</h1>
        <p>This is just a test</p>
      </section>
    `;
  }
}
```

Now we have the components that we want to show in the page.

## Create the routes
We need to create the routes and connect them somehow with the components.

So, let's do it in a easy way:
```js
// Routes 
const routes = [
  { path: '/', component: HomeComponent, },
  { path: '/page1', component: Page1Component, },
  { path: '/page2', component: Page2Component, },
];
```

## Router
How should the router look like?
Let's assume that our goal is to code something like that: 

```js
const router = () => {
  // TODO: Get the current path
  // TODO: Find the component based on the current path
  // TODO: If there's no matching route, get the "Error" component
  // TODO: Render the component in the "app" placeholder
};
```

Then let's start! :)

### Get the current path
The `location` object is excatly the tool we need.
> The Location interface represents the location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to. Both the Document and Window interface have such a linked Location, accessible via Document.location and Window.location respectively. ([MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Location))

One property of the location object is `location.hash`, which contains the part of the URL from '#' followed by the fragment identifier of the URL.

In other words, given this URL: `http://foo.bar/#/hello`, location.hash would be: '#/hello'.

So we need to extract from that string something we can use with out `routes`.

We remove the "#" char from and in case any hash value is provided, we assume it will be the base url: `/`.
```js
const parseLocation = () => location.hash.slice(1).toLowerCase() || '/';
```

At this point we solved the first "TODO" of the list:
```js
const router = () => {
  //  Find the component based on the current path
  const path = parseLocation();
  // TODO: If there's no matching route, get the "Error" component
  // TODO: Render the component in the "app" placeholder
};
```

### Get the the right component
Since we have the `path`, what we need to do is to get the first matching entry of the `routes`.

In case we can't find any route, that we just return `undefined`.

```js
const findComponentByPath = (path, routes) => routes.find(r => r.path.match(new RegExp(`^\\${path}$`, 'gm'))) || undefined;
```

We solve the next TODO now!
We use a "destructuring assignment" to assign the matching component to the  const `component`, which gets by default the `ErrorComponent`.
Since the "destructuring assignment" requires an object on the right-hand side and since our `findComponentByPath` function could return `undefined`, we provide in this case just an empty object `{}`.

```js
const router = () => {
  // Find the component based on the current path
  const path = parseLocation();
  // If there's no matching route, get the "Error" component
  const { component = ErrorComponent } = findComponentByPath(path, routes) || {};
  // TODO: Render the component in the "app" placeholder
};
```

Now we are ready to solve the third and last TODO: render the component in the app.

### Render the component
If you remember, our components have a `render` method that returns the HTML template.
So we have to put that template in the app `<section id="app"></section>`.

This is very easy, you know. 
We get the element using the id and put the content in the `innerHTML` property.
```js
document.getElementById('app').innerHTML = component.render();
```

The `router` is ready: 
```js
const router = () => {
  // Find the component based on the current path
  const path = parseLocation();
  // If there's no matching route, get the "Error" component
  const { component = ErrorComponent } = findComponentByPath(path, routes) || {};
  // Render the component in the "app" placeholder
  document.getElementById('app').innerHTML = component.render();
};
```

### Make it work
Even if the code would work, there's something sill missing. 
We are never calling the `router`! Our code right hasn't been executed yet.

We need to call it in 2 cases: 
1) On page load since we want to show the right content from the very first moment
2) On every location update (actually every "hash" location update)

We need to add to event listeners and bind them with our `router`.

```js
window.addEventListener('hashchange', router);
window.addEventListener('load', router);
```

That's it :)

Here you can find a live example: 
{% codesandbox wispy-flower-jwlwc %}

##
# Key takeaway points:
• Learn how Window.location works
• Learn how template literals work
• Learn how EventTarget.addEventListener() works

# Docs:
• [Window.location](https://developer.mozilla.org/en-US/docs/Web/API/Window/location) 
• [Template literals (Template strings)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) 
• [EventTarget.addEventListener() ](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) 

## About this post
I'm am running a **free** **JavaScript Learning Group** on [pixari.slack.com](pixari.slack.com) and I use this blog as official blog of the community. 
I pick some of the questions from the #questions-answer channel and answer via blog post. This way my answers will stay indefinitely visible for everyone."

If you want to [**join the community** feel free to click here](https://join.slack.com/t/pixari/shared_invite/enQtOTA5MzE0NzcwNzI3LTM5OGQ5MzNkMDA3ZTNkNTNmMmI4NTM5MGRiY2RiMDEyOGE0NGM3M2M3M2Y2NTNjNzZlMTY2NTY5ZmQwM2ZhZjk) or contact me: 

 - [@pixari on Twitter](https://twitter.com/pixari)
 - [@JSL_group on Twitter](https://twitter.com/JSL_group)
 - [raffaele.pizzari@gmail.com](mailto:raffaele.pizzari@gmail.com)