Nested routes using React Router v6
Today we’ll show you how to implement nested routes using React Router v6. We already written an article to explain how to add nested routes with React Router version 5.
Checkout more articles on ReactJS
We’ll stick with the prior representation moving forward. So please refer to the earlier article URL Parameters with React Router v6.
The location menu list will be added to the contact page in this example, and if someone clicks on the location link, the location page will be displayed inside the contact page.
Demo Application
Steps to implement nested routes using React Router v6
1. Project structure
Refer to the following project structure for nested routes.
- nested-routes-react-router-v6
- node_modules
- public
- index.html
- src
- About.js
- App.js
- Contact.js
- ContactLocation.js
- Home.js
- index.css
- index.js
- NotFound.js
- package-lock.json
- package.json
- README.md
If you compare it to the previous post, you will see that the src
directory now has an extra file called ContactLocation.js
.
2. Package version
In this example, we have used the following packages.
3. Add nested routes
First, we’ll create a ContactLocation
component to render the nested pages.
1 2 3 4 5 6 7 8 9 10 11 | import React from 'react'; import { useParams } from 'react-router-dom'; const ContactLocation = () => { const { id } = useParams(); return <div style={{ marginTop: 10 }}> <b>Selected Location: {id}</b> </div> } export default ContactLocation; |
Now, we have to set the routes for the nested component. Let’s add the following routes in the App.js
file.
1 2 3 | <Route path="contact" element={<Contact />}> <Route path="location/:id" element={<ContactLocation />} /> </Route> |
At last, we have to use <Outlet />
component that renders the next match in a set of matches.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import React from 'react'; import { Link, Outlet } from 'react-router-dom'; const Contact = () => { return <div> <h4>Contact</h4> <p>This is Contact page.</p> <p>Select location from the list.</p> <ul> <li><Link to="location/1">Location 1</Link></li> <li><Link to="location/2">Location 2</Link></li> <li><Link to="/contact/location/3">Location 3</Link></li> </ul> <Outlet /> </div> } export default Contact; |
Relative or absolute paths can be defined for nested route redirection, as you can see in the code above.
4. Output
Run the application and check the output in the browser.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂