Clue Mediator

Nested routes using React Router v6

📅September 7, 2022

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

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

import React from 'react';
import { useParams } from 'react-router-dom';

const ContactLocation = () => {
  const { id } = useParams();
  return <div 10="" style={{ margintop: }}>
    <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.

App.js

<route path="contact" element="{<Contact">}>
  <route path="location/:id" element="{<ContactLocation">} />
</route>
</route>

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

Contact.js

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</li>
      <li><link to="location/2">Location 2</li>
      <li><link to="/contact/location/3">Location 3</li>
    </ul>
    <outlet>
  </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..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project