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
:
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:
- a home page at
/
- a page to view many books at
/books
- and a page to view an individual book's details:
/books/{bookID}
wherebookID
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:
Now, functions to validate the home (/
) and books (/books
) 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:
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:
and for url parameters:
Finally, we can put these functions together inside the Router
component to render the correct content:
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:
Follow me on Twitter!
Top comments (0)