React Router Tutorial: Adding Navigation to your React App
Tags: react, router, app, devops
Published: 2020-05-22 17:46:32

*This article was written by Erin Doherty and was originally published on [Educative.io](https://www.educative.io/blog).*

In this React tutorial, we'll be taking a look at React router - a specific library for handling routes within a web app. At its core, what React Router does is conditionally render certain components to display depending on the route being used in the URL (`/` for the homepage).

**Why use React router?** It allows you to build single page web applications (SPA) with navigation. React Router uses component structure to call components, which display the appropriate information. React router also allows the user to utilize browser functionality like the back button, and the refresh page, all while maintaining the correct view of the application.

For this tutorial, you should feel comfortable with web development concepts such as DOM  (Document Object Model), HTML, npm, and JavaScript.  

Now, here's what will be covered:
* [What is React Router?](#what-is)
* [Client Side vs. Server Side](#client-side)
* [React Router vs. React Router DOM](#dom)
* [Single Page Applications (SPA)](#spa)
* [React Router Tutorial: Adding Navigation to your React App](#tutorial)
* [Benefits of React Router](#benefits)
* [Resources](#resources)

If you're new to React or need a refresher on the fundamentals, you can check out my article [What is React? A tutorial on how to get started](https://www.educative.io/blog/what-is-react-tutorial).


<br>

<a name="what-is"></a>

## What is React Router?

React router is a library that allows you to handle routes in a web app, using dynamic routing. Dynamic routing takes place as the app is rendering on your machine, unlike the old routing architecture where the routing is handled in a configuration outside of a running app. React router implements a component-based approach to routing. It provides different routing components according to the needs of the application and platform. The following illustration shows how react router’s dynamic routing works as compared to traditional static routing:

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

Here is a really simple single-page app (SPA) that implements routing using React Router. This code belongs to the `routes.js` files of a React app. To see the full app in action, visit my [original post](https://www.educative.io/blog/react-router-tutorial). 


```js
import React from 'react';
import { Home } from './views/Home';
import { About } from './views/About';
import { NavBar } from './components/NavBar';
import { Route, Switch, Redirect } from 'react-router-dom';

export const Routes = () => {
  return (
    <div>
      <NavBar />
      <Switch>
        <Route exact path="/Home" component={Home} />
        <Route exact path="/">
          <Redirect to="/Home" />
        </Route>
        <Route exact path="/About" component={About} />
      </Switch>
    </div>
  );
};
```

There is one component `NavBar` that appears on the top of the app and enables switching between different views namely, `Home` and `About`. The `router.js` file is where all the routes of the SPA can be defined.

In `routes.js`, first, the components, views, and required packages are imported (Line 1-5). Then all those routes are defined that the SPA can take, keeping the `Home` component the default route (Line 13-15). And then all the possible routes are simply added using the following template, between `<Switch>` tags:

```js
<Route exact path="/specifiedPath" component={componentName} />
```

The component (`componentName`) will be rendered when the `"/specifiedPath"` is visited on the web app.

Importing these routes from `routes.js` to `index.js` file, putting them inside a `<Router>` tag is all that is needed as the last step.

React Router can be installed using the npm cli utility:

```js
> npm install react-router-dom
```

… and then can be imported and used inside the SPAs.

<br>

<a name="client-side"></a>

## Client vs. Server Side
We can't have a conversation about routing and React Router without mentioning client side and server side. Client side is the browser. Its processing happens on the local machine – like rendering a user interface in React. Server side is where the information is processed and then sent through to a browser.

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

Server-side means that the action takes place on a web server. Most JavaScript can be done without access to a web server. Client-side means that the JavaScript code is run on the client machine or the browser when we’re talking about web applications. Server-side JavaScript means that the code is run on the server which is serving web pages.

<br>


## React Router vs. React Router DOM

React Router DOM is DOM bindings for the React Router, or in simpler terms React Router for websites. In contrast, React-Router-Native is bindings for an app development environment using React Native – most often mobile phone Operating Systems – like iPhone/iOS.
To return to our web vs. native development topics, React Router come in 2 flavors, just like React: 
* Web
* Native

<br>

<a name="spa"></a>

## Single Page Applications
Single page applications dynamically rewrite the web page with new data from the server, instead of the default method of the browser loading entirely new pages. When – you – the user, clicks a link, you don’t go to an entirely new page. Instead, the new context loads inline on the same page you’re already on – so only the necessary components of the page render. 

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

Click on Ms. Maisel:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6jjfx5enz45iw097yia8.png)

Single page applications can make the website seem more like a native app. A lot of web pages are written as single page applications where each component renders independently. 

Single page applications are where React Routing comes into play. When people use a website, there are some things they expect to work – like the back button on the browser, or the URL signifies the view they are currently looking at. This can get complicated for the developer to build in Single Page applications – there’s a “deep link” problem. Some piece of information on a Single Page app may be buried deep underneath many components, so how does the developer make sure the correct URL showing that component displays in the address bar? Through routing – which is why we’re learning about React Router.  React Router is a JavaScript library that provides routing capabilities to single page applications built in React. 

Conceptual steps to building a single page app:
* Main parent component
* Initial Frame: static (aka app frame)
   - Could be one invisible HTML element that acts as a container for all the web pages content, or could be a header, or title.
   - In the Dogs SPA graphic above – the two components on the left showing “Contact” and “Care 101” stay the same in both views of the SPA. The center section renders with a picture of Ms. Maisel when that link is clicked. 
* React Router defines a Routing Region
   - Navigation links
   - Container to load content into – in our picto graphic above – the center region where the picture of Ms. Maisel shows up. 
* Component provides the foundation for the navigation, browser history handling, so users can use the backward  & forward buttons.

<br>

<a name="tutorial"></a>

## React Router Tutorial: Adding Navigation to your React app

Let’s do a quick example to see the very basics of React Router – one step farther than a Hello World, but not by much. We’ll do React Router web for our example. First, we’ll follow some operational steps to get the React Router example going, then dive into the JavaScript code in depth.

**JavaScript**

```js
const {
  BrowserRouter,
  Route,
  Link
} = ReactRouterDOM

// Set up pages using the React Router Link element for navigation - instead of <a></a>
const App = () => (
  <div>
    <h1>React Router Example</h1>
    <ul role="nav">
      <li><Link to="/client">Client Side</Link></li>
      <li><Link to="/server">Server Side</Link></li>
    </ul>
     
    <div>
      <Route path='/client' component={Client} />
      <Route path='/server' component={Server} />
    </div>
  </div>
)

// Populate sample pages. 
const Client= () => <h3>What is client side?<body><li>Browser</li><li>Runs on local machine</li><li>React renders user interface</li><li>React Router adds clickable links</li></body></h3>

const Server= () => <h3>What is server side?<li>node.js - JavaScript everywhere!</li></h3>

//Render app into the root HTML DOM node
ReactDOM.render((
  <BrowserRouter>
    <App/>
  </BrowserRouter>
), document.getElementById('root'));
```


**HTML**

```
<div id='root'></div>
```

When you run the code, you should see this output:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/3d7pi99yspmboz5ujwzy.png)

These links will now be   clickable  thanks to React Router! Now you could  spruce this up and add CSS, but for this example, we'll keep it simple.  

Now, let's dive into what is actually happening with this code:

<br>

### Breaking down the JavaScript

**Part 1: `Render()` Function**


```js
//Render app into the root HTML DOM node
ReactDOM.render((
  <BrowserRouter>
    <App/>
  </BrowserRouter>
), document.getElementById('root'));
```

- Remember from the [earlier React article](https://www.educative.io/blog/what-is-react-tutorial) about the `render()` function? 

   - `Render()` is taking the logic from the React element in the JavaScript side, and displaying it in the User Interface. 
   - React elements are plain objects that are cheap to create, unlike DOM objects. Speed is a benefit of React. React DOM updates the root DOM node in the HTML window to display the rendering of the React element in the user interface.  
- `<BrowserRouter>` tags
   - Set up your app to work with React Router by wrapping the app in `<BrowserRouter>` element. Everything that gets rendered goes inside the `<BrowserRouter>` element. 
<App /> tag
- The app tag refers to the const App = () => App function in the JavaScript code. 

<br>

**Part 2: Sample Pages Section**

```
// Populate sample pages. 
const Client= () => <h3>What is client side?<body><li>Browser</li><li>Runs on local machine</li><li>React renders user interface</li><li>React Router adds clickable links</li></body></h3>

const Server= () => <h3>What is server side?<li>node.js - JavaScript everywhere!</li></h3>
```


- In this example, sample pages are made through HTML tags. In a real app, sample pages might be populated by an API, or be in their own separate JavaScript files in the same project, because pages can get complicated. 


<br>

**Part 3: App Function**

- Let’s start with `<Route>` tags. `<Route>` tags represent links between components. Route tags are React Router syntax similar to `<a>` tags in normal HTML.  


```js
<div>
    <Route path='/client' component={Client} />
    <Route path='/server' component={Server} />
</div>
```

- Here, we added 2 routes. Let's examine the first Route example client:
   - “`component={Client}`” tells JavaScript to link to the const Client sample page
   - `Route path='/client'` tells JavaScript to add “`/client`” to the URL when clicking that link
- App function: Link element – add clickable links!


```js
<ul role="nav">
      <li><Link to="/client">Client Side</Link></li>
      <li><Link to="/server">Server Side</Link></li>
</ul>
```

<br>

<a name="benefits"></a>

## Benefits of React Router:
- Add routing to different views/components on Single Page Applications
- Composable
- Easily add links after designing the webpage
- React Router conditionally renders certain components depending on the route from the URL. 

<br>

## Wrapping up
Now that you've explored React Router and it's capabilities, it's time to start building your own React applications.

The [Road to React: the one with hooks](https://www.educative.io/courses/road-to-react-with-hooks) is a great project course. Throughout, you'll be learning all the ins and outs of React and by the end you will have built a fully-functional Hacker News App that will be a great addition to your portfolio.

<br>

<a name="resources"></a>

## Resources

**Articles**
* [The Evolution of React: V16 and Beyond](https://www.educative.io/blog/the-evolution-of-react)
* [React hooks design patterns and creating components without class](https://www.educative.io/blog/react-hooks-components-and-design-patterns)
* [Understanding Redux: Beginner's Guide to modern state management](https://www.educative.io/blog/understanding-redux)

**Other helpful resources**
* [React for Front-End Developers](https://www.educative.io/track/advanced-front-end-developer)