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
You may also like-
No comments:
Post a Comment