Wednesday, June 4, 2025

Nested Route in React Router With Example

In this post we'll see how to configure nested routes or child routes in React Router.

Nested routes in React

You can nest a route inside another route which establishes a parent route-child route relationship.

<Route path="parent" element ={<Parent />}>
    <Route path="child" element = {<Child/>}/>
</Route >

With this kind of nested route, child URL path is relative to the path to parent which means this route configuration creates both /parent and /parent/child URLs.

With nested routes you can also control the rendering of the child routes which can be rendered with in the context of parent using the Outlet component.

import { Outlet } from "react-router";
export default function Parent() {
  return (
    <div>
      <h1>Parent</h1>
      {/* will render <Child/> */}
      <Outlet />
    </div>
  );
}

Example of nested route can be seen in this post- Using NavLink in React Router where route configuration is as shown here-

<Route path="/" element {<NavigationNavLink />}>
  <Route index element={<Home />} />
  <Route path="about" element={<About />} />
</Route>

With this configuration "/" and "/about" are nested paths with in the root URL.

Dynamic nested route in React

You can also nest a dynamic route so that dynamic path segment can be mapped to a route. For example, if you have a product page that shows product names and clicking on any product displays the details of that product. This means you need to add the id part as dynamic path segment so that any path in this format /product/{ID} is mapped to the route.

<Routes>
  <Route path="/" element={<NavigationNavLink />}>
    <Route index element={<Home />} />
    <Route path="product" element={<RouteProduct />}> 
      <Route path=":productId" element={<RouteProductDetails />} /> 
    </Route>
    <Route path="about" element={<About />} />
  </Route>
</Routes>

As you can see here this particular nested route-

<Route path="product" element={<RouteProduct />}> 
  <Route path=":productId" element={<RouteProductDetails />} /> 
</Route>

Will map to any path like- /product/101, /product/23 and so on.

That's all for this topic Nested Route in React Router With Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Index Route in React Router
  2. Routing in React With Example
  3. React Declarative Approach
  4. React Virtual DOM

You may also like-

  1. React create-react-app Project Structure
  2. JavaScript Rest Parameter
  3. ArrayList in Java With Examples
  4. Count Number of Times Each Character Appears in a String Java Program
  5. Java Stream API Interview Questions And Answers
  6. What is Client Side Routing in Angular

No comments:

Post a Comment