DEV Community

Cover image for Simple Router for React Apps
Caleb Lewis
Caleb Lewis

Posted on

Simple Router for React Apps

Tools like React Router provide a nice framework with which to think about and implement routing in your app. But what if you have a relatively small project that doesn't need complex routing logic?

Enter: the browser's window.location object.

It provides all you need to create a simple 'routing' system for your app. Here's, for example, what the window.location object would like for this url: http://localhost:3000/books/123456?key=abcd&searchterm=cats:

window.location object

So, what if we created a Route functional component that parsed the location.href and/or the location.path looking for strict matches, and otherwise returning a 404 page.

Suppose we had a small library app and wanted to show just three pages:

  1. a home page at /
  2. a page to view many books at /books
  3. and a page to view an individual book's details: /books/{bookID} where bookID comes from a database (as-a-service like firebase).

Since only have a few simple requirements, we could just use window.location to do our own routing.

First we'll create an enum encapsulating the concept of having different 'pages' or routes:

routes enum code

Now, functions to validate the home (/) and books (/books) routes:

valid books and home routes

We return null here to represent that the given location is indeed not the one we want to render; we want to render the route that is alternatively returned.

Now for the individual book route:

individual book route

This illustrates how quick and easy it can be to make a simple and powerful routing mechanism. Here, we use regex to match against the location's pathname to strictly determine whether the path is a valid one.

For variable paths and url parameters, it's simple to parse them from the url. Here's an example of getting a path parameter:

path parameter fetching code

and for url parameters:

url parameter fetching code

Finally, we can put these functions together inside the Router component to render the correct content:

router component code

Here, we put the validators into an array, and iterate over them until we get a match. Once the first passing validation happens, break takes us out of the iterator.

NOTE: that since we're iterating over the validation functions in an array, the order of the validations is something to pay attention to

Then we check to make sure that if window.location didn't pass any of our validations, we set the route to NOT_FOUND.

Finally, we check the route via a switch statement, and show the page we want to render!

All you need next is to put Router in your index.js file:

index.js file

Follow me on Twitter!

Top comments (0)