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:


With a React SPA you have something like this:


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>
      <Route path="/animals/dog">
        <Dog />
      <Route path="/animals/cat">
        <Cat />
      <Route path="/about">
        <About />
      <Route path="/">
        <Home />

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 and a user tries to visit: you want their browser to actually load, 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: no matter which path your user goes to.

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


  • 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 ;)