Nested Routes in React JS
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.
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
1 2 3 4 5 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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; |