How React Router Works

React.js Feb 05, 2020

This post was inspired by a friend of mine (rowan).

When I was making a web app using React recently, I came across an interesting technology known as React Router. I thought it was pretty neat and it fit my use case for a project so I decided to use it. Little did I know how powerful it was, and how much I'd need it.

So let's talk about the most basic question: What IS React Router? In a simplistic sense, it's a way to navigate in React. For example, let's say I'm making my own blog. I'd want to have multiple paths users can visit. If they visit /home for example, I'd want to show them the home page. If they visit /posts on the other hand, I'd show them a list of blog posts. In a normal case, when a user visits one of those URLs from another (e.g. going to /posts from /home), a request would be sent to the server, to tell the client what resource to serve.

This is where React Router stands out.

Instead of server-side navigation, React Router navigates on the client side. This means that instead of defining what happens when a user visits /posts on my server, I can now define what renders for /posts in React itself. This might not seem that powerful, but think about it - the more and more users I would gain for my blog, the better and better my app would scale, since my server isn't constantly spammed with requests to access a resource. Clients don't use as much network data, and servers don't use up too much resources. Overall, it's pretty awesome.

So, how does this look in a code implementation?

Well, let's take a look at the example on React Router's quickstart guide:

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

export default function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/users">Users</Link>
            </li>
          </ul>
        </nav>

        {/* A <Switch> looks through its children <Route>s and
            renders the first one that matches the current URL. */}
        <Switch>
          <Route path="/about">
            <About />
          </Route>
          <Route path="/users">
            <Users />
          </Route>
          <Route path="/">
            <Home />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

function Home() {
  return <h2>Home</h2>;
}

function About() {
  return <h2>About</h2>;
}

function Users() {
  return <h2>Users</h2>;
}
React Router example usage

This is a pretty basic example of React Router, and there are a few parts to it. First is Router. This is the component which contains all your route declarations and stuff like that. Similar to the Provider component to those familiar with Redux :). Inside our Router, we see a few things, notably Link, Switch, and Route.

Route

<Route path="/about">
  <About />
</Route>

So the first thing we're gonna talk about is Route. Looking at the code, let's look at the first Route declared, the one where it says path="/about". So looking at the props for the Route, it can be inferred that it's a definition for the path /about. But then what does it do when the path matches? Looking inside the Route, it has children, specifically another component defined below - About. When a user navigates to /about, React Router will render the children inside the Route definition, which in this case happens to be the About component.
TL;DR: A Route will render its children when a user navigates to the path provided as one of its props.

Switch

<Switch>
  <Route path="/about">
    <About />
  </Route>
  ...
</Switch>

Next up, we got Switch. If you know some code, (I hope you do), you'll know about a switch statement - a piece of code that takes in anything, say, a variable that can be any number between 1 and 10 - and inside it are case statements, which, when given a value to check for, tell the code what to do when a variable is a specific value. React Router has something similar going on with the Switch component. Inside the Switch component are Routes, and when a user visits a certain path, the Switch statement inside the Router is basically used to find the first matching path, or default to some Route you have set up as a 404 page.
TL;DR: A Switch statement is where all your Route definitions should go; it should be at the top level inside a Router.

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

Finally, we have Link, sadly not the one and only from The Legend of Zelda (a great game, I might add). Links are kind of like the React Router equivalent of anchor, or a, tags. They take one prop - to - which can be used to specify a path to navigate to once the Link is clicked. Using React Router's Link component ensures compatibility with the other parts of React Router, building a seamless user experience with little to no disruptions.
TL;DR: A Link is basically the React Router version of an a tag, but built for React Router. Use it. Please.

Well, I hope I did my job. This guide probably won't be enough to get you using React Router right this second, but there are definitely places to look to start out. I still highly recommend reading the documentation for React Router since it is pretty robust and easy to follow, even having a quick-start section of its own. Thanks for reading and have a great day!

Arnav M. (giant flying kitty)

17 year-old living in the Bay Area. Obsessed with learning and honing skills when it comes to coding. Currently proficient in Node.js and React.js, while learning a lot more! Part of Nexus Creative.