October 25, 2023

Index Route in React Router

In this tutorial we'll see what is index route in react router.

Index routes in react-router

In most of the cases you'll have a default child route matching the parent route's exact path.

For example, in the following route definition you can notice one parent route with path as "/" and also a child route with the same path as "/".

export const router = createBrowserRouter([
    {path: "/", element: <Navigation />,
     children: [
        {path: "/", element: <Home /> },
        {path: "/about", element: <About />}
     ]
    },        
])

In such cases you can configure child route as an index route. That tells the router to match and render this route when the user is at the parent route's exact path.

All you have to do is use { index:true } instead of { path: "" } to configure a route as an index route.

Index route React example

We'll use the same example as used in the post- React Router - NavLink in react-router-dom

Only change that is needed is in src\components\Routes\route.js

import { createBrowserRouter } from "react-router-dom";
import About from "./about";
import Home from "./home";
import Navigation from "./navigation";

export const router = createBrowserRouter([
    {path: "/", element: <Navigation />,
     children: [
        {index: true, element: <Home /> },
        {path: "/about", element: <About />}
     ]
    },        
])

In the child route for Home page instead of path, index: true is used to make it an index route so that it becomes a default child route. Whenever user is at the parent route's exact path this default child route is matched.

That's all for the topic Index Route in React Router. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment