Routing with React

React websites are Single Page Applications (SPAs). They usually consist of a single index.html and some .js files.

In a html only website, if you wanted multiple pages you'd have a folder structure like this:

website/
  index.html
  about.html
  animals/
    dogs.html
    cats.html

With a React SPA you have something like this:

website/
  index.html
  index.js

But what if you also want an /about, /animals/dogs and animals/cat page like the other example?

We can use react-router.

React Router

react-router-dom is a library you can use to make your Single Page React website appear to have multiple urls.

Setting up routes

react-router-dom provides components to help with this problem. <Router>, <Switch> and <Route>.

Here is you setup the example from above:

() => {
  return <Router>
    <Switch>
      <Route path="/animals/dog">
        <Dog />
      </Route>
      <Route path="/animals/cat">
        <Cat />
      </Route>
      <Route path="/about">
        <About />
      </Route>
      <Route path="/">
        <Home />
      </Route>
    </Switch>
  </Router>
}

Linking to pages

To link to another page in your react website you can use react-router-dom's <Link> component e.g.:

 <Link to="/about">About</Link>

These links do not reload your entire website like <a href="/about">About</a> would.

This means once your initial react site is loaded, it never reloads even as the user clicks on links to navigate around, this is very fast!

Rewrite rules gotcha

If you host your site on https://example.com and a user tries to visit: https://example.com/animals/dog you want their browser to actually load https://example.com/index.html, which will invoke react-router-dom and show them your <Dog> component.

This is not the default behavior of most hosting solutions / web servers.

It varies depending on how you're hosting your site, but it can usually be fixed by having a 'rewrite rule' which tells your web server to always serve: https://example.com/index.html no matter which path your user goes to.

So Google: React SPA rewrite rule <your tool here>

Examples:

  • React SPA rewrite rule nginx
  • React SPA rewrite rule netlify
  • React SPA rewrite rule firebase

And someone on the internet will have already come up with a guide to help you ;)