Introducing React Router

In this tutorial, we are going to get you started with react-router-dom using an example React application showing you how to use different concepts such as Link and NavLink for creating links (instead of anchors) in the React way, Switch and exact for enabling exclusive routing and browser routing history.

Perhaps the most suitable way to see how React Router v4 works is by writing a simple multiple-page React app using the new router concepts. Our example app will have routes to home, about, contact, login, register, and profile components/pages. But first, let's have a tour of React Router v4 concepts and how they differ from React Router v3?

Before v4 there was React Router v3, React router v4 is a complete re-write so what’s the difference between these two React routers? here is a summary list of most differences:

  • With React router v4, routing is not centralized anymore instead it becomes a part of the rest of the app layout and UI.
  • Browser specific routing components live in react-router-dom instead of react-router so imports need to be changed to be from react-router-dom package.
  • Introducing new components such as BrowserRouter and HashRouter for specific use cases (see below).
  • No more use of {props.children} for nesting components in v4 React Router.
  • React Router v3 routing rules were exclusive meaning only one route will be matched at one time. For v4, routing rules are inclusive meaning multiple routes can be matched and then rendered.

React-router-dom is the version of React Router v4 designed for web applications, React Router v4 was divided into three packages:

  • react-router: common core components between dom and native versions.
  • react-router-dom: the dom version designed for browsers or web apps.
  • react-router-native: the native version designed for react-native mobile apps.

react-router hosts the core components for routing for React applications, react-router-dom provides browser-specific components for routing web apps and react-router-native provides specific components for react-native or mobile apps created with React Native. So you should either install react-router-dom or react-router-native as both export their corresponding environments components plus what react-router exports.

Since we are building a web application, not a native mobile app we need to install react-router-dom package, so inside your React project run the following command using your terminal (Linux or MAC) or command prompt (Windows):

npm install --save react-router-dom
  • BrowserRouter: This is a sub-class or a concrete implementation of the Router interface that makes use of HTML5 history API to sync your UI with the current browser’s URL or actually the URL's path i.e window.location.
  • HashRouter: Just like the previous router but only uses the hash part of the URL i.e window.location.hash.
  • MemoryRouter
  • NativeRouter: Used for routing inside react-native mobile apps.
  • StaticRouter: Used for static routing just like React Router v3.

There are many types of Router components, among them < BrowserRouter > and < HashRouter > for client-side React apps. If you are using a dynamic service that can handle dynamic URLs then you need to use the BrowserRouter component but if you are using a server that only serves static files then a HashRouter component is what to be used in this case.

The < Route > component is one of the most useful components of React Router v4 and the idea behind it is simple, wherever you want to render something when only there is a match with the location’s path you can use a Route component.

The Route component takes many properties such as:

  • path property: of type string, it holds the name of the path to be matched.
  • component property: it holds the name of the component to be rendered if there is a match.
  • exact property: this property tells Route to exactly match the path (see inclusive and exclusive routing)
  • strict property: this property tells Route to match only a path that has a trailing slash.

There are two other properties that can replace the component property to tell the Route component what it needs to render when there is a match:

  • render property: a function that returns a React element. More useful for inline rendering or for wrapping rendered components.
  • children: also a function that renders a React element. Except that this one will always render even if there is no path match.

Most of the time, you will use the component property but there are also many situations when you’ll have to use either render or children properties instead. The three methods will be passed these three props:

For example:

Using component:

Will render the HomePage component when the browser's location path matches exactly /.

Using render:

For inline rendering:

For wrapping:

Using children:

For more information about how React Router v4 matches paths see path-to-regexp the module used for matching paths.

Usually, there are various parts of the pathname used to pass information between different routes of an application so how do we capture these variables and pass them to components? We can just append the name to be used for the variable plus a colon: to the end of the route’s path, for example:

When there is a path match an object which has the following properties will be created and passed to the component:

  • url: the matched part of the URL.
  • path: simply the path.
  • isExact: equals True if path equals exactly the current location’s path-name.
  • params: an object containing URL parameters.

Links are React Router v4 components designed as a replacement of anchor links to create navigation elements which enable users to navigate between differenet pages of React apps. Unlike anchors ,which reloads the whole page, Links only reload the portion(s) of the UI that match(s) the browser’s location path.

A Link component takes a to property which tells React Router the destination to navigate to. For example:

import { Link } from 'react-router-dom'
const Nav = () => (
<Link to='/'>Home</Link>

When clicked will take us to a location with path: /

the to prop can either take a string or a location (pathname, hash, search, and state) object, for example:

Link can take also another property: replace if True, when clicked the link entry will be replaced in the history.

NavLink is a subclass of Link which adds styling information to the rendered element(s), for example:

Now let's write an example React app which shows you how to use BrowserRouter to implement routing.

First, we import the necessary routing components such as Route and BrowserRouter

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

Next we create the base layout component, besides common HTML tags we also use React Router v4 components Link and Route:

Next we create our pages:

And finally we create the App component which BrowserRouter component to hold our base layout component then render the app.

As you can see, it’s very easy to use the React Router v4 components to create apps with routing.

In our example app, we used the prop exact in the Route for component HomePage

That’s because React Router v4 uses inclusive routing instead of exclusive routing used by React Router v3 so without exact property the home component will be rendered with all other components, for example when the user visits /login path both / and /login paths will be matched and their corresponding components LoginPage and HomePage will be rendered. But that's not the behavior we are looking for, that's why we need to add the exact prop which tells the Route component to match exactly the / path.

Now let's see how we can use inclusive routing to our advantage, lets suppose we have a sub-menu component that needs to be available only when we are on the profile page We can easily change our basic layout to add this requirement:

So as you can see all Routes with path ‘/me’ will be rendered when we visit ‘/me’ path not just the first match, that’s inclusive routing.

Exclusive routing is the inverse of inclusive routing, it was the default routing in React Router v3 where only the first match is rendered so what if you want exlusive routing back? that also can be done using v4 router using the Switch component. In a Switch component only the first child < Route > or < Redirect >, that matches the location, will be rendered. For example:

React Router v4 provides a history object that exposes a simple API with different implementations (HTML5 history API for dom, legacy hash history for dom, in-memory history for react-native) to manage/manipulate browser history.

You can also navigate inside your React application using methods from the history object, for example:


Which are equivalent to:

Whenever you want to redirect to another location, you can place a component which is when rendered will redirect to the location specified in to prop that can either be a string or a location object, for example:

Or simply:

React Router v4 makes it dead easy to create React apps with complex UIs that has routing between different portions, you can simply declare a Router component such as BrowserRouter or HashRouter and put, inside of that, a bunch of child Routes components that have props which indicate the path to be matched and the component to be rendered inclusively whenever there is a match (i.e all matched Routes will be rendered). In case you need to do exclusive rendering (Just like React Router v3: i.e only the first matched Route will be rendered) then you can simply use a Switch component where only one child (the first found) will be rendered. You can also pass different information between routes using parameters that can be captured and retrieved from the match object which gets created once a match is established and then passed to the currently rendered component. Finally, all building blocks or components of React Router v4 designed for web apps routing are available and can be imported from react-router-dom.

Developer and technical author. Read more articles at Techiediaries