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.

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

Nested routes using React Router v6 - Clue Mediator
Nested routes using React Router v6 – Clue Mediator

Steps to implement nested routes using React Router v6

  1. Project structure
  2. Package version
  3. Add nested routes
  4. Output

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.

react
^18.2.0
react-router-dom
^6.3.0

3. Add nested routes

First, we’ll create a ContactLocation component to render the nested pages.

ContactLocation.js

Now, we have to set the routes for the nested component. Let’s add the following routes in the App.js file.

App.js

At last, we have to use <Outlet /> component that renders the next match in a set of matches.

Contact.js

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..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *