Seleccionar página

React Router v4: Client-side routing tutorial

When we design a new web aplication we start thinking about some basic concepts like components, data, actions or pages. One of the key concepts of a web application is routing. We have to construct links and routes that will allow users to move around and navigate through the web application. This React tutorial will explain how React faces the routing problem.
“In a web application, routing is the process of using URLs to drive the user interface (UI)” – Meteor Developers

What is react-router?

One of the reasons of being so lightweight is that React library is mainly focused on components and doesn’t provide a solution for other problems like routing. react-router is the standard routing library of React and it is divided into 3 libraries:
  • react-router: core library with core routing components and functions
  • react-router-dom: specific browser components and functions
  • react-router-native: specific React Native components and functions.

Installation of react-router

The installation is straightforward and you only need to install directly the specific library depending on the development environment (browser or mobile app). Like React, React Router DOM is published to npm so you can install it with NPM package manager:
npm install --save react-router-dom

The Router

The Router component is used to provide routing functionalities to our application. It will keep the user interface of your application in sync with the URL. As it only can contain one child, we normally use the following coding strategy for adding routing features:
// react-native
import { NativeRouter } from 'react-router-native'

// react-dom (what we'll use here)
import { BrowserRouter } from 'react-router-dom'

ReactDOM.render((
<BrowserRouter>
<App/>
</BrowserRouter>
),document.getElementById('app'))

In the example above, our application will be defined by the App component. The Router also manages the history object, the one in charge of keeping the current location and rendering when it changes are fired.

Route component

The <Route> component is the most important component. Each <Route> component will match with a route and render a component depending on the URL pathname of the moment. As you can imagine, a Route will be defined by specifying two properties: the path and and component. Every time the path matches with the path specified in the Route, it will render the component defined in the “component” property.

// react-dom (what we'll use here)
import { BrowserRouter } from 'react-router-dom'

ReactDOM.render((
&amp;amp;lt;BrowserRouter&amp;amp;gt;
&amp;amp;lt;App/&amp;amp;gt;
&amp;amp;lt;/BrowserRouter&amp;amp;gt;
), el)

const App = () =&amp;amp;gt; (
&amp;amp;lt;div&amp;amp;gt;
&amp;amp;lt;Route path='/' component={Dashboard} /&amp;amp;gt;
&amp;amp;lt;Route path='/profile component={Profile} /&amp;amp;gt;
&amp;amp;lt;/div&amp;amp;gt;
)

const Dashboard= () =&amp;amp;gt; &amp;amp;lt;h1&amp;amp;gt;You are in the Dashboard&amp;amp;lt;/h1&amp;amp;gt;
const Profile= () =&amp;amp;gt; &amp;amp;lt;h1&amp;amp;gt;You are in the Profile&amp;amp;lt;/h1&amp;amp;gt;

In the example above, when the user navigates to “http://yourdomain.com/” the <Dashboard> component will be shown and when going to “http://yourdomain.com/profile” the <Profile> component will be the one displayed. It is important to mention that the Router will ignore the domain part of the URL for matching the routes.

Navigate with links

Links are used to navigate through your application and are rendered like regular HTML anchors. Let’s add Links to our previous example:

See the Pen Simple React Router example by Jon Vadillo (@jonvadillo) on CodePen.light

Index route

Previously in React Router v3 we used the IndexRoute concept to define the component displayed in the home page of our web application. When users visited “/” the component defined in the IndexRoute tag was rendered. Now in in React Router v4 the concept of an IndexRoute doesn’t exist and instead you must use the exact property.

&amp;amp;lt;Router&amp;amp;gt;
&amp;amp;lt;div&amp;amp;gt;
&amp;amp;lt;Route exact path=&amp;quot;/&amp;quot; component={Home}/&amp;amp;gt;
&amp;amp;lt;Route path=&amp;quot;/about&amp;quot; component={About}/&amp;amp;gt;
&amp;amp;lt;/div&amp;amp;gt;
&amp;amp;lt;/Router&amp;amp;gt;

Nested routes

In the same way you build nested React components, you can also create nested routes structures. The following code shows how to build nested routes with react-router library.

See the Pen React Nested Router example by Jon Vadillo (@jonvadillo) on CodePen.light

URL params

URL params are passed to the component and can be read using the properties object. In the previous code, we were reading the URL parameter

const About = (props) =&amp;amp;gt; (
&amp;amp;lt;div&amp;amp;gt;
&amp;amp;lt;h3&amp;amp;gt;Welcome to the About Page&amp;amp;lt;/h3&amp;amp;gt;
&amp;amp;lt;h2&amp;amp;gt;{props.params.name}&amp;amp;lt;/h2&amp;amp;gt;
&amp;amp;lt;/div&amp;amp;gt;
)

Conditionally Render using the Switch Component

The component is used to render only the first child that matches the location, instead of rendering every route that matches.

import { Switch, Route } from 'react-router'

&amp;amp;lt;Switch&amp;amp;gt;
&amp;amp;lt;Route path=&amp;quot;/about&amp;quot; component={About}/&amp;amp;gt;
&amp;amp;lt;Route path=&amp;quot;/:user&amp;quot; component={User}/&amp;amp;gt;
&amp;amp;lt;Route component={NoMatch}/&amp;amp;gt;
&amp;amp;lt;/Switch&amp;amp;gt;

In the example above, if the user visits “/about” path, the Switch component will stop trying to match routes once it has matched the first one (“/about”). This would be completely different without the Switch component, as it would render , and components.

What’s next?

In this article we have talked about the solution that react-router library provides for adding client-side routing functionalities to our web application. Client-side routing has several performance advantajes comparing to the traditional server side routing architecture where we need to ask to the server for a new rendered HTML page every time the user wants to navigate through our app. If you read my previous articles about the introduction to React and how to build complex components, now you have all the tools needed for building a complete react app. Happy coding!   If you want more articles + tutorials like this, subscribe to my newsletter – I send out a new one every week or so. Remember, if you liked the article you can share it using the buttons below!

Sources