Routing with React Router 4

- JavaScript Developer and Blogger
Published: Fri Jul 07 2017

In this post I will show how to use React Router 4 to add routing to a React application.

I am new to routing in React, but I really like the simplicity of the Router.

So far, the biggest difference from other routers I’ve used is that a route serves as both route definition and router outlet.

Meaning, the Route element not only defines meta data for the route, it also marks where the routed component is inserted in the DOM.

A route can be as simple as a single component, but you can also define more complex, nested routes.

Nested routes just means you have a multi level url where each fragment maps to a component in a component hierarchy.


Let’s create a demo application with some basic routing.

I start by defining the Router collection in my outermost component like so:

import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import GreetingDemo from './pub-sub/greeting-demo'; import { About } from './about' render( <div> <h1>React Demos</h1> <Router> <div> <Route path="/about" component={About}></Route> <Route exact path="/greeting" component={GreetingDemo}></Route> </div> </Router> </div>, document.getElementById('root') );

The greeting route is an example of a single level route. The /greeting url is mapped to a single Greeting component.

The /about route is slightly more complicated since it nests two components. The full url will be /about/descr, but I start by defining the "/about" root segment in the outer Route element.

Inside the mapped About component I define the second part of the route as a new Route element. Both segments work in tandem to define the final /about/descr route.

Here is the About component with its nested Description component:

import React, { Component } from 'react'; import { Route } from 'react-router-dom'; class Description extends Component { render() { return ( <div> <div>More to come later</div> </div> ); } } export class About extends Component { render() { return ( <div> <h4>About</h4> <Route exact path='/about/descr' component={Description}></Route> </div> ); } }

The source is available on Github in case you want to try it out.

I invite you to follow me on twitter