Wednesday, June 4, 2025

Index Route in React Router

In this post we'll see what are Index routes in React Router.

You can think of index routes as nested routes that don't have their own path. Consider this route definition which was used in post- Using NavLink in React Router.

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

Requirement here is; when the user accesses the root URL, navigation menu should be rendered (NavigationNavLink component) and Home component should also be rendered. That is why path="/" is used in both the routes.

In such scenario child route can be defined as an index route making it a default child route which should be rendered into their parent's <Outlet/> when the path for the parent route is accessed.

If we take the route definition as stated above, child route can be configured with the index prop to make it an index route.

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

Using index with createBrowserRouter

If you are using createBrowserRouter to configure routes then index routes are defined by setting index: true on a route object without a path

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

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


Related Topics

  1. Routing in React With Example
  2. Link in React Router With Example

You may also like-

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

No comments:

Post a Comment