React Router: How to add child routes

For react router 4 and above

Avery Duffin

Hopefully by now you are familiar with react. But one of the most important things when building your single page web apps is understanding routing. Lucky for us react has made routing really easy.

When you first start writing react apps you probably started with a bunch of these:

const NewComponent = ({shouldDisplay}) => {
return shouldDisplay ? <div>HA!</div> : null

Well you could do that for your routing but as your components and apps get bigger things are going to get more hairy.

Probably arguably the best library for routing is react-router. Instead of taking a deep dive into react-router. Lets talk about how you can make your router use sub-routes or child routes. If you need some more information on how to use react router check out the website here.

First make sure you import the library and components you need.

import { 
BrowserRouter as Router,
from 'react-router-dom'

Now first thing we will need is a component that renders our routes.

now there’s one line here that’s a bit tricky. On route line 23, I used render instead of component. That’s because I wanted to be able to pass props into my component on that route.

My goal here is to have a page that renders Landing on the route ‘/’ and a route that renders About with sub routes on ‘/About’.

Now we need to make the components Landing and About.

We’ll make them really simple components.

Really simple now if you run this code in your react app you’ll see that the route /Landing will render a page with contents

This is a Landing Page

and route /About with contents

About Page

So now we want the contents of the about page to have some links that will display different content on the page but also keep the content the about page has already

We do this by using <Route /> and <Link /> components from react router inside the about section.

Another thing I will use is the match prop that comes across auto-magically from react router.

heres what the code looks like

now your code should be complete. The app should render and about page with links to change the paragraph text below the title.

I hope you were able to learn something! Happy coding!

If you found this helpful. Leave me a comment or follow me on twitter.