Clue Mediator

Nested Routes in React JS

📅September 14, 2019

In this article we will show you how to create nested routes in React JS. It will help you to load sub routes in the main routes.

Nested routes with React Router, Understanding Nested Routing in React, react router nested routes v4, react-router-dom nested routes, Nested Routes in React JS.

We are going to continue with the previous example. So refer the previous article URL Parameters with React Router.

https://youtu.be/QXTb5pf-B34

The complete guide of Routing in ReactJS

Way to implement Nested Routes in React JS

  1. Implement Nested Routes with Example
  2. Output

1. Implement Nested Routes with Example

Create SubContact file to load the nested routes.

SubContact.js

import React from 'react';

const SubContact = ({ match }) => <b>Selected Contact: {match.params.id}</b>

export default SubContact;

In the Contact.js file, we need to import the react router components because we need to implement the subroutes inside the Contact Component and load the selected component.

Contact.js

import React, { Component } from 'react';
import { Route, Link } from 'react-router-dom';
import SubContact from './SubContact';

class Contact extends Component {
  render() {
    return <div>
      <h4>Contact</h4>
      <p>This is Contact page.</p>
      <p>Select contact from below list</p>
      <ul>
        <li>
          <Link to="/contact/1">Contact 1 </Link>
        </li>
        <li>
          <Link to="/contact/2">Contact 2 </Link>
        </li>
        <li>
          <Link to="/contact/3">Contact 3 </Link>
        </li>
      </ul>
      <Route path="/contact/:id" component={SubContact} />
    </div>
  }
}

export default Contact;

2. Output

Output - Nested Routes in React JS - Clue Mediator

Output - Nested Routes in React JS - Clue Mediator

Demo & Source Code

Github Repository StackBlitz Project