Routing React Apps: The Complete Guide

Routing being a key aspect of web applications (and even other platforms) could not be left out in React. We can make full fleshed single page applications with React if we harness the powers of routing. This does not have to be a manual process, we can make use of React-Router.

In this guide, we will touch almost every aspect related to routing in React and there will be a demo so you will as well have something to play with.

Prerequisites

You are not going to only learn how to route a React application but I will also show you basics of tooling React using Babel, NPM and Webpack. Before we start building, let's set that up and see what our folder structure will look like.

First Create a new project:

mkdir scotch-cars
cd scotch-cars
npm init

Follow NPM init wizard then install the following tooling dependencies:

The most important aspect of a Webpack config is the exported config object. The minimal code above just needs an entry point, entry which is where bundling needs to begin from. It also requires an output, output which is where the bundled result is dumped and then module, which defines what loaders should be used during the bundling process. In our case, babel is the loader we need.

We need to explicitly tell Babel which presets it should make use of. You can do this with package.json or in a .babelrc file. .babelrc file is what you will see in most projects, so let's follow that:

touch .babelrc

Define the presets:

{
"presets" : ["es2015", "react"]
}

To run Webpack we have to use a reference to the bin every time which would cause friction to our dev process. What we can do is setup scripts in the package.json to help us with that:

Setting Up React for Routing

Now that we have got a simple environment for React to live in, next step is to setup it up for routing.

React likes to keep things as simple as possible and that is why the core library just does exactly what React is about, components. Routing, DOM rendering and other logics are abstracted to a different library. To use routing, we have to pull down React, React Router and React DOM:

The path attribute defines the route URL and component attribute defines the component for this route.

This kind of routing is different from what you might have seen in other UI frameworks and it is known as component routing. It is very easy to reason about because routes are also treated the same way components are treated. Routes are first class components.

We discuss the ugly URL later in this article.

More Routes

You do not need routing if the only thing you want is a single path/page as our existing example shows. Let's add more routes to the application:

Nesting (Route Ownership)

Component routes are first class components in React, so when it comes to parenting/ownership, the same rule applies. Our app is expected to have a navigation menu that is accessible by all the main routes. We can make another parent route for all the existing routes which will have the nav-bar:

At the moment our app defaults to hashHistory and that is what is responsible for the ugly URL. browserHistory is the recommended option for user consumption. We just need to tell React-Router to use browserHistoty:

You also need to set the base URL in the head of index.html before it works as expected:

<!-- ./public/index.html -->
<base href="/" />

This works fine until you navigate to another page and reload:

This shouldn't surprise you though because now we are making a request back to server which does not even handle a wildcard route. Let's use express to fix this by creating a backend custom server with a wildcard route URL that takes us back to where we were when a reload happens:

Links

Our application is becoming more interesting and it is time to add some route links. We need to navigate with clicks and not changing URL values. Before we discuss how to add links, let's populate our application with mock cars:

We updated our Car component to present a list of data. The data is a static array, no need for the complexity of request as this article is only about routing.

With some static data available, let's tackle this topic. Links in React routing work well with the anchor tag but this is not recommended. Link is a component that uses anchor internally and is the recommended way for displaying links because it plays nicer with React Router:

<Link to="/">Home</Link>

That is how links are used and the to property defines the path we want to navigate to on click just like href. Let's update our Main component to apply links:

Let's use this ID to filter the cars array. Before we can do that we need to move the cars data array to a file that both Car and CarDetail component can have access to it. That should be the root then we can pass it down to the components as route props:

Bonus: Protecting Routes

It is a common practice to restrict users from accessing a particular resource because of limitations placed on there roles in the given app. We can't afford to allow a buyer have access to admin dashboard where prices can be changed. Though this logic is something that MUST be handled backend but for a better user experience, it is also important on the frontend:

We are using the onEnter lifecycle event to listen to when this route will be hit. Once that happens, a check is run to determine if the authenticated user is an administrator or not.

Conclusion

This was a long read but if you followed along, you have the basics of what you need to get going with React. This article does not just serve as a tutorial but also a reference for your day by day routing solutions in React with React Router.