React - Router v4

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

React Router is a routing service that can runs:

  • client side (web)
  • server side
  • native side

3 - Installation

If you are writing an application that will:

  • run in the browser
# It contains a binding with DOM + react router
npm install --save react-router-dom
  • not run in the browser
npm install --save react-router

4 - Component

4.1 - Router

A React router is a component that's not going to display anything until we configure a route.

In v4, there is 3 type of router:

  • The <BrowserRouter> creates a browser history. It uses the HTML5 history API (pushState, replaceState and the popstate event)
  • the <HashRouter> creates a hash history,
  • and the <MemoryRouter> creates a memory history.



4.2 - Route


import { BrowserRouter, Route } from 'react-router-dom'
      {/* add the routes here */}
    <Route path='/about' component={About} />
    <Route path='/contact' component={Contact} />
), document.getElementById('app'))


React Router comes with a <Link /> component that lets you navigate around your application.

Link is almost identical to the a tag, except that:

  • it's aware of the Router (the back and forward browser action are working)
  • it knows if the path it links to is active so you can style it differently (activeClassName or activeStyle attribute)


import React from 'react'
import { Link } from 'react-router'
export default React.createClass({
  render() {
    return (
        <h1>React Router Tutorial</h1>
        <ul role="nav">
          <li><Link to="/about" activeStyle={{ color: 'red' }} >About</Link></li>
          <li><Link to="/contact" activeClassName="active" >Contact</Link></li>
        {/* add this */}
  • The rendering when clicking is
// at /about
// at /repos

NavLink is a link aware of the history. It can add a special class activeClassName or activeStyle when the link is the actual browser path.


import { NavLink } from 'react-router-dom'
<NavLink to="/about" activeClassName="selected">About</NavLink>

4.5 - URL Params

Consider the following URLs:


These URLs would match a route path like this:



  • :name are URL parameters whose values will be made available to route components on this.props.params[name].

5 - Documentation / Reference