React Router Quick Start Guide

By Sagar Ganatra
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Free Chapter
    Introduction to React Router 4 and Creating Your First Route
About this book

React Router is the routing library for React, and it can be used in both React Web and React Native applications. This book is a simple way to get started with React Router and harness its full power for your applications.

The book starts with an introduction to React Router and teaches you how to create your first route using the React component. You will then learn about configuring your routes, passing parameters, and creating nested routes. You will be introduced to various components in React-Router and learn different configuration options available for these components. You will then see how to use the Redirect and Switch components. For even greater flexibility, you will learn about BrowserRouter, HashRouter, NativeRouter, and StaticRouter.

By the end of the book, you will have set up a project with React Router and make routing configuration work in a server-side rendered React application, a mobile application built with React Native and also understand how Redux and React-Router can be used in the same application.

Publication date:
September 2018


Introduction to React Router 4 and Creating Your First Route

Single page applications (SPAs) have become the de facto standard for developing applications for the web. Many JavaScript libraries and frameworks have emerged that help frontend engineers in developing SPAs. These include React, Angular, Ember, and Backbone, to name a few. These libraries or frameworks abstract native APIs and provide services and components that can be used to build applications quicker. SPAs are an excellent choice for providing a fluid user experience; as the user traverses through the site, HTTP requests are triggered, and only certain sections of the page are updated, instead of requesting the server for the entire page.

React is an open source JavaScript library that helps you in building user interfaces and the view layer in web and mobile applications. It encourages developers to visualize the view layer as a collection of components that can be reused throughout the application. Most frontend frameworks include a routing package that enables you to update sections of the page when the user clicks through various links provided on the site. A router in a frontend framework listens to the changes in the URL and keeps the application in sync by rendering the corresponding view components. For example, when the user visits '/dashboard', the page would render various dashboard components, such as charts and tables, and when the user visits, say, '/user', the page would list various user attributes. In a React-based application, a Router library is required, since React does not ship with one. React-Router is one such popular routing library built completely with React. The library includes various components that can be used to render views as the user navigates through the application. Apart from matching the URL and rendering the view components, React-Router has several features that help you to configure the routes easily.

In this chapter, the following topics are discussed:

  • A brief look at React: This section introduces you to some of the core concepts in React, such as component-based architecture, creating components in React, and how data can be provided to child components in the application tree
  • Introduction to React-Router: Here, we first create a React application using the create-react-app CLI and then add the React-Router library (the 'react-router-dom' package) as a dependency
  • Creating your first route: After adding React-Router as a dependency, the application's first route is created using the <BrowserRouter> and <Route> components

A brief look at React

React is a JavaScript library that provides a set of components and services and enables you to build user interfaces.

Here is a quote from

"React is a declarative, efficient, and flexible JavaScript library for building user interfaces."

The library is developed and maintained by Facebook and is licensed under MIT. It's extensively used in building various applications at Facebook, including Facebook web and Instagram web.

React enables you to build view components that get updated when the application's state changes. The state here could refer to the underlying domain data, or it may reflect where the user is in the application journey. React ensures that the view components reflect the application state.

Here are some of the important features of React:

  • JSX: Components in React applications use an XML/HTML-like syntax, known as JSX, to render the view elements. JSX allows you to include HTML in your JavaScript/React code; the familiar syntax of HTML with attributes in your React component's render function does not require you to learn a new templating language. This JSX is then used by preprocessors such as Babel to transpile HTML text to JavaScript objects that the JavaScript engine can understand.
  • One-way data binding: React applications are organized as a series of nested components; a set of immutable values are passed to the component's renderer as properties in HTML tags. The component does not modify the properties (or props) it receives from its parent; instead, the child communicates the user actions to its parent component and the parent component modifies these properties by updating the component's state.
  • Virtual DOM: In React, for every DOM object, a corresponding virtual DOM object is created that has the same set of properties as the real DOM object. However, the virtual DOM object lacks the power to update the view when the user interacts with the page. Components in React re-render the view elements whenever a change in state is detected, and this re-render updates the virtual DOM tree. React then compares this virtual DOM tree with the snapshot that was created before the update to determine the DOM objects that changed. Finally, React modifies the real DOM by updating only those DOM objects that changed.

Component-based architecture in React

Since its release in 2013, React has redefined the way that frontend applications should be built. It introduces the concept of component-based architecture, which, in essence, allows you to visualize your application as if it were made up of tiny, self-sustained view components. These view components are reusable; that is, a component such as CommentBox or Footer encapsulates the necessary functionality and can be used across the pages in the site.

A page in this context is itself a view component that is composed of other tiny view components, as shown here:

<Brand />
<NavLink key=”1”>
<NavLink key=”2”>
<Grid data="stockPriceList">
<Footer />

Here, <Dashboard> is a view component that encompasses several other view components (Header, SideNav, ContentArea, and Footer), which in turn are made up tiny components (Brand, NavLink, Chart, and Grid). The component-based architecture encourages you to build components that provide certain functionality and are not tightly coupled with any of their parent or sibling components. These components implement certain functionality and provide an interface through which they can be included in the page.

In the preceding example, a <Grid> component would include features such as rendering data in rows and columns, providing search functionality, and also an option to sort the columns either in ascending or descending order. The <Grid> component would implement all of the aforementioned features and provide an interface through which it can be included in the page. The interface here would include the tag name (Grid) and set of properties (props) that accept the values from its parent component. Here, the <Grid> component could interface with the backend system and retrieve the data; however, this would make the component tied tightly to the given backend interface, thus not making it reusable. Ideally, a view component would receive data from its parent component and act accordingly:

<Grid data="stockPriceList" />

Here, the <Grid> component receives a list containing stock price information through its data prop and would render this information in a tabular format. A component that includes this <Grid> component can be termed a Container component and Grid as a child component.

A Container component is also a View component; however, its responsibility includes providing its child components with the necessary data to render. A Container component could initiate HTTP calls to a backend service and receive the data required to render its child components. In addition to that, the Container component is also responsible for the positioning of the individual view components in its view area.

Creating a React component

A React component is created by extending the Component class provided by React as follows:

import React, { Component } from 'react';
import './button.css';

export class Button extends Component {
render() {
return (
<button className={this.props.type}>

Here, the Button class extends React's Component class and overrides the render method. The render method returns the JSX, which will be rendered on the DOM when the page loads. The type and children properties are available in this.props. React allows you to pass data to its components through props and does so by using the following syntax:

import React, { Component } from 'react';
import { Button } from './components/Button/button';
import './App.css';

export default class App extends Component {
render() {
return (
<div className="App">
<Button type="secondary">CANCEL</Button>
<Button type="primary">OK</Button>

Here, we have wrapped the Button component inside a parent component, App, to render two button elements. The type attribute is consumed by the Button component to set the class name (className) of the CANCEL and OK buttons and text mentioned inside the Button tag. This can be referenced using the children property. The children property can be plain text or other view components. The child component gets a reference to the data provided by its parent component using this.props. The children property in 'this.props' provides a reference to all the child elements included between the tags by the parent component. If you've used Angular in the past, consider the preceding snippet as similar to how you would include elements using ng-transclude in AngularJS, or ng-content in Angular.

Here, the <App> component contains the <Button> component and can be referred to as a container component, which is responsible for rendering the buttons on the page.

The next step is to render the <App> component on the DOM. The <App> component serves as a root component, that is, a root node in a tree. Every component in the application has the <App> component as its top-most parent component:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(<App />, document.getElementById('root'));

This code is included in index.js, which imports the React and ReactDOM libraries. The ReactDOM library has a render method, which accepts the component to be rendered as its first parameter, and a reference to the DOM node where the root component has to be rendered.

When the app is run, the content inside the <App> component is rendered:


Introduction to React-Router

React-Router is a routing library for SPAs built with React. React-Router version 4 is a complete rewrite and embraces the React philosophy of component-based architecture.

This is from the React-Router documentation (

"React Router is a collection of navigational components that compose declaratively with your application. Whether you want to have bookmarkable URLs for your web app or a composable way to navigate in React Native, React Router works wherever React is rendering--so take your pick!"

React-Router can be used wherever React can be applied; that is, React-Router works both in the browser and in the native environment with React Native.

The library is divided into three packages:

  • react-router: Common core components for DOM and Native versions
  • react-router-dom: Components for use in browser and web applications
  • react-router-native: Components for use in native applications built with React Native

The library provides various components that can be used to add routes dynamically to your application. The dynamic routing in React-Router v4 allows you to specify application routes as the user progresses through the application journey. Frameworks such as AngularJS and Express require you to specify the routes upfront, and this routing information is required when the application bootstraps. In fact, the earlier versions of React-Router followed the same paradigm and required the routing configuration to be available upfront.

Apart from dynamic routing and providing fluid navigation in a React application, the library includes various features that are available in traditional websites. These include the following:

  • Navigating backward and forward through the application, maintaining the history, and restoring the state of the application
  • Rendering appropriate page components when presented with a URL (deep-linking)
  • Redirecting the user from one route to the other
  • Support for rendering a 404 page when none of the routes match the URL
  • Support for hash-based routes and pretty URLs with HTML5 mode
It's a common misconception that React-Router is the official routing solution provided by Facebook. In reality, it's a third-party library and is licensed under MIT.


Getting started with React-Router

Let's create a React application and then add React-Router as a dependency.

To create a React application, we will use the create-react-app CLI. The create-react-app CLI makes it easier to create an application that already works. The CLI creates a project scaffold so that you can start using the latest JavaScript features, and also provides scripts to build applications for a production environment. There are various React and React-Router starter kits available; however, using create-react-app helps in demonstrating how React-Router can be added to an existing bare-bones React application.

The first step is to install create-react-app globally using NPM, as follows:

npm install -g create-react-app

The CLI requires the node version to be greater than or equal to 6, and the npm version to be greater than 5.2.0.

Once the CLI has been installed, we will create a new application using the create-react-app command, as seen here:

create-react-app react-router-demo-app

The following output is displayed when create-react-app completes the installation of packages:

Inside that directory, you can run several commands:
npm start
Starts the development server.

npm run build
Bundles the app into static files for production.

npm test
Starts the test runner.

npm run eject
Removes this tool and copies build dependencies, configuration
and scripts into the app directory. If you do this, you can't
go back!
We suggest that you begin by typing:
cd react-router-demo-app
npm start

If you used the yarn package manager (, the npm commands in the preceding snippet would be replaced with yarn.

The react-router-demo-app directory is created during installation (if it doesn't already exist). Inside the directory, the following project structure is created:

| |--favicon.ico
| |--index.html
| |--manifest.json
| |--App.css
| |--App.js
| |--App.test.js
| |--index.css
| |--index.js
| |--logo.svg
| |--registerServiceWorker.js

The CLI installs all the necessary dependencies, such as Babel, to transpile ES6 code to ES5, thus enabling you to leverage the latest JavaScript features. It also creates a build pipeline configuration with the help of webpack. Post-installation, no additional configuration is required to start or build the app. As noted in the preceding output, you can start the app using the npm start command and build a production-ready app using npm build.

On running npm start, the application is compiled and will open a browser window with a Welcome to React message displayed, as shown here:

In the index.js file, the ReactDOM reference is used to render the application's root component as follows:

ReactDOM.render(<App />, document.getElementById('root'));

The <App> component marks the beginning of the tree that will get rendered when the application starts.

Adding the React-Router library

Now that we have our sample application up and running, let's add React-Router library as a dependency using npm:

npm install --save react-router-dom

This command will download and add react-router-dom to the /node_modules directory. The package.json file now includes this as a dependency:

"dependencies": {
"react": "^16.4.0",
"react-dom": "^16.4.0",
"react-router-dom": "^4.3.0",
"react-scripts": "1.1.4"
At the time of writing this book, version 4.3.0 of react-router-dom was available. You can try the alpha and beta builds by mentioning react-router-dom@next when including the library using npm.

Defining application routes

The react-router-dom package includes a <BrowserRouter> component, which is used as a wrapper before adding routes in the application. To use React-Router in the React Native application, the react-router-native package is used. This will be discussed in detail in later chapters. The <BrowserRouter> component is an implementation of the router interface that makes use of HTML5's history API to keep the UI in sync with the URL path.

The first step is to wrap the application's root component with <BrowserRouter>, as shown here:

import { BrowserRouter } from 'react-router-dom';

<App />

Wrapping your application inside <BrowserRouter> will create an instance of history for our <App> component, giving all of its child components access to props from the native browser history API. This allows components to match against URL paths and render the appropriate page component.

History is a JavaScript library that lets you manage history stack navigation and helps in persisting state between sessions.

Routing in React-Router isn't actually routing—it's conditional rendering of components based on the pattern that matches with the current URL path. To define a route, we need two pieces of information: the URL path to match with and the component to render. Let's create two components, HomeComponent and DashboardComponent, that render at /home and /dashboard respectively.

In src/components/home/home.component.js:

import React from 'react';

export const HomeComponent = () => (
Inside Home route

And in src/components/dashboard/dashboard.component.js:

import React from 'react';

export const DashboardComponent = () => (
<div className="dashboard">
Inside Dashboard route

The import statement is required since we are returning JSX from the preceding components.

The next step is to define a route using the Route component (from 'react-router-dom'). The Route component accepts several props, but for the purpose of this example, we will use path and component.

In App.js:

class App extends Component {
render() {
return (
<div className="container">

export default App;

Here, we're defining routes within the 'render' method of the <App> component. Each <Route> component has a path prop, which mentions the URL path to match, and a component prop, mentioning the component to render once the path matches the URL.

In the preceding example, the component was created without extending React's component class. If a component, created by extending React's component class, is provided as a value to the component prop, then the component's lifecycle methods, componentWillMount and componentWillUnmount, are called every time that <Route> renders the component.

When you run the app (npm start) and visit localhost:3000/home, HomeComponent is rendered and the message Inside Home Component is displayed. Similarly, DashboardComponent is rendered when you visit localhost:3000/dashboard.

<BrowserRouter> creates a History object, which it uses to keep track of the current location and re-render the site whenever it changes. <BrowserRouter> makes the History object available to its descendent child components through React's context. A Route component that does not have <BrowserRouter> as its parent will fail to work.

Also, it's a requirement that <BrowserRouter> has only one child element. In the following snippet, <BrowserRouter> is given two child elements:

component={HomeComponent} />
component={DashboardComponent} />

The preceding code will result in an error, such as A <Router> may have only one child element. To resolve this, you could either move these routes into a component and provide the component reference, or wrap the <Route> components in the preceding snippet inside another element, such as div or React Fragment.

A React fragment is used to group a list of children without adding extra nodes to the DOM. A fragment is used when the component returns multiple elements.

Apart from BrowserRouter, there are other types of routers in the React-Router library: HashRouter, MemoryRouter, and StaticRouter. These are discussed in later chapters.



React is a JavaScript library used to build user interfaces. Unlike libraries such as Angular and Ember, which include a routing package, the React library does not include any components or services that help in routing. React-Router is a routing library that can be used in any React application, web or native. React-Router version 4 is a complete rewrite of the earlier versions and all of its components are written in React. The library includes the packages react-router-dom for use in web applications; react-router-native, for use in native applications built with React-Native; and react-router, a core package that both react-router-dom and react-router-native have a dependency on.

The create-react-app CLI is used to quickly scaffold a React application. It includes build configuration scripts that can be used to generate builds for development and production environments. The react-router-dom package is then added as a dependency to the application. The package includes the <BrowserRouter> component, which implements a History interface. The application's root component, <App />, is wrapped inside React-Router's <BrowserRouter> component to make the History object available to all the components in the application tree.

To create our first route, the <Route> component is included. It accepts path and component as props, and renders the component when the browser's URL matches the <Route> path.

In Chapter 2, Configuring Routes - Using Various Options in the Route Component, the <Route> component props are discussed in detail. Also, we will take a look at the various props that the rendered component receives, and consider how these props can be used to create nested routes.

About the Author
  • Sagar Ganatra

    Sagar Ganatra is a frontend engineer and an architect from Bangalore, India. He has more than a decade of experience in developing web and mobile applications. He specializes in architecting projects using JavaScript and frameworks such as React, Angular, and Node. His previous books include Kendo UI Cookbook and Instant Kendo UI Mobile, both published by Packt Publishing. He also writes about frontend technologies in his blog, sagarganatra (dot) com.

    Browse publications by this author
React Router Quick Start Guide
Unlock this book and the full library FREE for 7 days
Start now