Using React Router 4: Lesson 7 of 12

Child Routes

Up Next

Using Switch

Autoplaying in 7 seconds!


Child Routes

It's great that we can have all our routes in one place. However, this could be hard to manage in the future when we have tens or hundreds of routes in our application. One way we can keep things a bit cleaner is by using child routes. Child routes are just routes that are displayed inside another route. This means that there can be more routes inside a component that is rendered by another route.

One place this can help us is with the routing to /users/:userId. We know that we only want this displayed over the users table. We also know that currently both show when we go to that route because both paths match that route. Therefore, this is a perfect situation where a child route can be used. We can make the route that displays the UserInfo component a child route of the route that displays the Users component! Let's do that now.

Cut out the /users/:userId route from src/fe/components/Cms/index.js and paste it just before the closing Page tag in the render method of our Users component.

  <Button positive onClick={this.handleNewUser}>New User</Button>
  <Route path="/users/:userId" component={UserInfo} />

Also, make sure to move the import for the UserInfo component and add an import for the Route component.

import { Link, Route } from 'react-router-dom';
import UserInfo from './UserInfo';

That's it! Notice how everything works the same, but we are utilizing child routes to do so! Sweet!

We can take this a step further and make everything in the CMS portion of the application be under a route. Therefore, all routes in the CMS would be child routes of that initial route. Update the App component to look like so.

import React from 'react';
import { Route } from 'react-router-dom';
import Cms from './Cms';

const App = () => (
  <div className="app-routes">
    <Route path="/" component={Cms} />

export default App;

We have imported the Route component and then added a new route that matches all URLs at the root level and renders our Cms component. This may seem unnecessary at the moment, but later in the series when we add a login page, this top level routing will be important.

View the application in the browser and notice how everything works the same. However, we are using child routes to organize our routing a bit better.

It works out well that we have moved these around because in the next video, we will discuss the Switch component and how it will enable us to show only one route when multiple routes match.

Alex Sears

2 posts

Developing is not only my job but also my passion. I love to teach myself new things as much as I love teaching others. The more people we get involved in this little thing we call "web development," the better we can make it. I mean, we always need more cat videos, right?