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
- Routing in React JS
- URL Parameters with React Router
- Nested Routes in React JS (You are here...)
- Multiple parameters with React Router
- What’s new in React Router version 6
Way to implement Nested Routes in React JS
- Implement Nested Routes with Example
- 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