Handling multiple pages with the external component React Router DOM
Published: 2021-06-04 12:25:07

{% youtube yQf1KbGiwiI %}
*Video tutorial for this article*

React Router DOM is an external component that allows you to build bigger projects by separating your project into different pages.

---

# Pre-requisites
[What is a Single Page Application](https://www.youtube.com/watch?v=xfGciVdbktI) (SPA): An excellent short video explaining what a single page application is and why they are so important.

---

# Quick disclaimer
After watching the SPA video above, we can expand about this world of SPA's using React and React Router DOM (I will refer to it as Router from now on to keep it short).

The Router simulates multiple pages with a little trick of changing the browser URL using JavaScript. It is like typing `google.com` and then `google.com/search` but without pressing the enter key to change the page. This allows the Router to tell React it has to render different content based on the URL.

The router can utilize this trick to pass information as well. For example, adding an "`?`" at the end of the URL like `google.com/search/?cats` or `google.com/search/?dogs` will allow the Router to use that keyword as a variable and send it across pages.

---

# Intended result
We will have by the end of the article: [React Router DOM interactive example](https://fe-react-router-dom.web.app).

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qrk7ygtn7jiywwryi2sv.png)
Figure 1: Collage of the pages we intend to replicate.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w2poj5kbtx5ehydu00ke.png)
Figure 2: The app hierarchy diagram.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l4dl2uc8hchtkx621yt1.png)
Figure 3: React Router DOM most-used components.

### Legend:
* 🟦 **Blue**: Component created by us.
* 🟥 **Red**: Browser Router external component.
* 🟩 **Green**: Switch external component.
* 🟪 **Purple**: Route external component.
* 🟨 **Yellow**: Link external component.

--- 
# Getting started
Just by looking at the diagram, you can see how big this article will be. Now it should start making sense why it is best to teach certain React concepts in a different order.

To tackle this project we will focus on 3 areas:
1. [How to install the Router](#guide-install)
1. [How to set up the App component](#guide-app)
1. [How to set up the Header component](#guide-header)

<span id="guide-install">&nbsp;<span/>
### How to install the Router:
First, we need to install the external component using NPM:

```
npm install --save react-router-dom 
```

<span id="guide-app">&nbsp;<span/>
### App component:
Then we proceed to import and utilize the Router components, similar to what we did in the previous article.

```jsx
import { BrowserRouter, Switch, Route } from "react-router-dom";

import HeaderBar from "./components/HeaderBar";
import PageA from "./components/PageA";
import PageB from "./components/PageB";
import PageC from "./components/PageC";

export default function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <HeaderBar />
        <Switch>
          <Route component={PageA} path="/" exact />
          <Route component={PageB} path="/page-b" />
          <Route component={PageC} path="/page-c" />
        </Switch>
      </BrowserRouter>
    </div>
  );
}
```
Let's break the new code into detail:
1. We import not 1 but 3 components from `react-router-dom`: `BrowserRouter`, `Switch`, and `Route`.
1. `<BrowserRouter>` wraps around everything. This is because anything inside it will have access to the web browser URL as a state variable.
1. `<Switch>` is the area where you want your navigable components to appear.
1. `<Route>` is the component that holds our individual pages. It has 2 important properties:
  1. `component`: Receives the component you want to use as a page.
  1. `path`: The browser's route that will allow users to navigate directly to this page.

**Note 1:** Watch out the moment you do the import. React has a library called `react-dom` (without the word router). React uses this library to navigate between components inside other components. Choosing the wrong import library will lead to errors with messages that make no sense.

**Note 2:** The header bar is outside of the `Switch` because we do not want it to change when we navigate between pages. However, it is inside the `BrowserRouter` because it has links that need to interact with the web browser URL.

**Note 3:** The first route is `/` to represent the home page, and this route needs the word `exact` to inform the Router to not confuse it with other routes starting with `/` but with more words after it.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n9kscca2q1oo18rx9w7j.png)

<span id="guide-header">&nbsp;<span/>
### Header Bar component:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ofqe2infnmahvvqqibsw.png)
Figure 4: The header bar component.

```jsx
import { Link } from "react-router-dom";

export default function HeaderBar() {
  return (
    <header className="header">
      <Link to="/">Page A</Link>
      <Link to="/page-b">Page B</Link>
      <Link to="/page-c">Page C</Link>
    </header>
  );
}
```

Lets analyze the code:
1. We import `Link` from `react-router-dom`, just like we did on App.jsx with the other Router components.
1. `<Link>` behaves like an anchor or button tag. It has the property called `to`, where you need to write the same route you put in the `<Route path="" />` property.

---

# Conclusion

This covers the basics of Router navigation. In class, we will cover more complex cases like using the URL to pass variables between pages.

For now, we can move to the next article: [Manage server state with useEffect hook](https://dev.to/softwaredevacademy/manage-server-state-with-useeffect-hook-3hbc) to learn how to fetch data in React.

---

# Additional reading:
[React Router Tutorial](https://www.youtube.com/watch?v=Law7wfdg_ls): A 30 min video that explains everything you need to know about this external component. It may be long, but it explains the advanced cases like sending variables through the URL.

---

# Credits
Cover: Photo by <a href="https://unsplash.com/@heidifin?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Heidi Fin</a> on <a href="/collections/86774607/now-what?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>