Adding React router to your app
Tags: tutorial, javascript, react
Published: 2019-04-30 12:47:49

_original post @ [Linguine Blog](https://blog.linguinecode.com/post/add-react-router-to-react)_

So your cat app is growing and you want to make it easier for your users to digest the content.

Great! Let’s add React Router DOM to your React cat application.

## What is React Router DOM

React Router DOM is a React library for the web. It utilizes another core library called React Router.

It’s main purpose is to allow the engineer to create routes for a React single page application.

Simple enough.

## The React Router goal

<figure class="wp-block-image">![Cat React app diagram](https://daqxzxzy8xq3u.cloudfront.net/wp-content/uploads/2019/04/29152336/cat-app-with-react-router.jpg)</figure>

The goal for this tutorial is to build a cat application that has 3 different routes.

The first route is going to be the home page, that displays the list of cat names.

And each cat item is a link that takes the user to that cat item unique URL route.

2 pages so far.

The third page is going to be the, add a cat page. It’s a simple form that allows your add a new cat.

I’ll also be using the new React hook API, so if you’re not familiar with it, please read a previous article on it. [Intro to React hooks](https://blog.linguinecode.com/post/getting-started-with-react-hooks).

## Installing React dependencies

In the terminal, I’m going to run this command:

<mark>npm install –save react react-dom react-router-dom react-scripts</mark>

We’re going to install React, React Router DOM, and React Scripts.

React Scripts is the command tool that is used for Create React App. It will helps us develop faster.

You’re package.json file should look like similar to this.

<figure class="wp-block-image">![React router package json file](https://daqxzxzy8xq3u.cloudfront.net/wp-content/uploads/2019/04/25120447/react-router-package-json-file.png)</figure>

## The project structure

<figure class="wp-block-image">![React router app structure](https://daqxzxzy8xq3u.cloudfront.net/wp-content/uploads/2019/04/29152446/react-router-app-structure.jpg)</figure>

The project structure is going to be fairly simple.

In the root of the project I’m going to have a <mark>public</mark>, and <mark>src</mark> directory.

The <mark>public</mark> directory holds our index.html skeleton framework.

The <mark>src</mark> directory will hold the React code.

Inside the <mark>src</mark> directory I’ve added another directory called <mark>pages</mark>.

<mark>pages</mark> will hold 3 React JavaScript files.

One to add a new cat, another to view a list of all the cats, and the last one to view a specific cat.

We also have the <mark>routes.js</mark> file. This file is a configuration file that will be an array of React routes.

Each object inside the routes array will contain data such as path value of the page, and what page React component to render when the URL path matches.

And of course, the <mark>App.js</mark>, this file will glue everything together and be the main file that holds the app logic, and state data.

## Building the list of cats view

<figure class="wp-block-image">![react render loop concept](https://daqxzxzy8xq3u.cloudfront.net/wp-content/uploads/2019/04/29152548/cat-list-loop.jpg)</figure>

In the _CatList.js_ file I added the following code.

<figure class="wp-block-image">![](https://daqxzxzy8xq3u.cloudfront.net/wp-content/uploads/2019/04/28021417/react-router-with-link-1024x925.png)</figure>

In this file I’m importing a React Component called <mark>Link</mark> from the React Router DOM node module.

The <mark>Link</mark> component allows us to wrap an HTML element or a React component to act as link, and it helps users navigate through the React routes.

Now, the <mark>CatList</mark> component accepts a prop called cats.

The React prop _cats_ needs to be an array of objects which gets loop through the array **map** function, and outputs list items that links to the interior view of a cat.  

<div class="wp-block-image">

<figure class="aligncenter">![Cat list react output](https://daqxzxzy8xq3u.cloudfront.net/wp-content/uploads/2019/04/28164503/cat-list-react-output.jpg)</figure>

</div>

## Creating the React form

Before I get started creating the single view for a cat. I need to be able to populate the list of cats.

This app will require a React form that allows some user input.

This React form will also be it’s own React route.

The code will live in a file called <mark>AddCat.js</mark>.

<figure class="wp-block-image">![](https://daqxzxzy8xq3u.cloudfront.net/wp-content/uploads/2019/04/28165424/react-form-add-cat-853x1024.png)</figure>

There’s a lot to digest here, so I will break it down.

In line 5, I’ve created a function called <mark>generateCat</mark> that chooses a random cat image that I have in my project, and generates the URL source for that image.

In line 12, I’m using the React hook, <mark>useState</mark>, to keep track of the new cats’ name.

And I’m changing the value of the cats’ name inside a <mark>onChange</mark> event in the input HTML element.

Now, when the user is ready to submit the new cat, they will click on the submit button.

The submit button has a <mark>onClick</mark> event that checks for a couple conditions.

One, it checks if the a custom property, <mark>onSubmit</mark>, has been provided by the parent React Component.

It then checks if the user has even entered a cat name.

If those 2 conditions pass, then it passes down some cat information to the React parent component such as the cat name, a slug, and the random cat picture that was generated.

Which in this case, the parent React component is in the <mark>App.js</mark> file.

As for the slug, it’s using a custom helper function that turns a name to a url endpoint.

It strips the white space, and any other special characters that don’t belong in the url.

For example, it will convert the name, “Mr. Frizzle” to “mr-frizzle”.

<figure class="wp-block-image">![React form view](https://daqxzxzy8xq3u.cloudfront.net/wp-content/uploads/2019/04/28171035/react-form-add-cat.jpg)</figure>

## Building the single view

Since we know what the data is going to look like from the form above, than we can start making assumptions how to filter and find the right cat for the single view.

<figure class="wp-block-image">![Getting access to history object with React router dom withRouter](https://daqxzxzy8xq3u.cloudfront.net/wp-content/uploads/2019/04/28171641/single-cat-view-921x1024.png)</figure>

On line 2, I’m importing a HOC (higher order component) from React Router DOM called <mark>withRouter</mark>, and I’m wrapping it around the <mark>SingleCat</mark> component.

<mark>withRouter</mark> lets a React component to have access to the history, location, and match object.

This is important because this React component needs access so it may attempt to get the unique cat slug in the URL, and find the object in the cat list that contains that unique slug.

In line 5, I’m initiating another <mark>useState</mark> hook, and a <mark>useEffect</mark> hook.

When the component mounts, the code will grab a parameter called **name** aka the slug.

It will then run an array filter method to look for the cat object that contains that slug value.

If the filter method returns an empty array then it will send the user back to the home page.

And if the filter method does return an object, then it will trigger the <mark>useState</mark> hook to update the variable value of **cat**.

Once the variable **cat** has a value, we will render out the data of the cat.

<div class="wp-block-image">

<figure class="aligncenter">![](https://daqxzxzy8xq3u.cloudfront.net/wp-content/uploads/2019/04/28182804/mr-frizzle-output.jpg)</figure>

</div>

## Creating React Router config file

<figure class="wp-block-image">![React router config file](https://daqxzxzy8xq3u.cloudfront.net/wp-content/uploads/2019/04/28182350/react-router-config-file.png)</figure>

This config lives in the <mark>route.js</mark> file.

The only purpose of this file is to import all the pages, and assign them a path value for the React route component that I’m about to use.

## Gluing React with its routes

Now for the file that glues everything together, <mark>App.js</mark>.

<figure class="wp-block-image">![](https://daqxzxzy8xq3u.cloudfront.net/wp-content/uploads/2019/04/28183009/react-router-route-components-553x1024.png)</figure>

Don’t let all the HTML markup scare you. The job for this file is really simple.

If you take a look at the top, you’ll see that I’m importing a few React components from the React Router DOM library.

The first import is the <mark>BrowserRouter</mark> component, that gets used in line 16.

<mark>BrowserRouter</mark> uses the HTML 5 history API, and must be used before adding any routes.

The next component, and probably the most important one, is the <mark>Route</mark> component.

The <mark>Route</mark> component is responsible to display the React component assigned to it, only when the location (url) matches.

You can see me using the Route component in line 30 as I’m looping through the route configuration that were created previously.

The Route component accepts a property called _path_.

This property accepts a regular string or a regex expression as a path. The path property does not need to be provided also.

If a Route component is not given a path value, then the component attached to it will always be shown.

So it’s highly recommended that you add a path value.

In line 34, I’m attaching the React component that is defined in the route configuration file, and I’m tossing a couple custom properties for the list page, and the add a cat page.

In line 10, I’ve also created another state property called **cats**.

That variable is responsible for tracking and holding all the cats that a user has added.

## Conclusion

As your application grows, it will require routes and pages views to be created.

React Router DOM, allows you to create routes really easily, and provides other helper functions and tools to allow users to navigate through your React app.

Github source: [with-router](https://github.com/rleija703/react-examples/tree/master/examples/with-router).