Reputation: 6462
I don't understand what the purpose of using an IndexRoute and IndexLink. It seems that in any case the code below would have selected the Home component first unless the About path was activated.
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="about" component={About}/>
</Route>
vs
<Route path="/" component={App}>
<Route path="home" component={Home}/>
<Route path="about" component={About}/>
</Route>
What's the advantage/purpose here of the first case?
Upvotes: 113
Views: 88527
Reputation: 25
In React Router v6, an index route is a child route without a path. It shows content by default when the parent route is visited directly.
For example: In the code:
<Route path="app" element={<AppLayout />}>
<Route index element={<p>List</p>} />
<Route path="cities" element={<p>List of cities</p>} />
<Route path="countries" element={<p>Countries</p>} />
<Route path="form" element={<p>Form</p>} />
</Route>
Visiting /app will render the index route: <p>List</p>.
Visiting /app/cities will render <p>List of cities</p>.
Index routes are great for:
Showing a default page when no specific child route is defined or matched.
An index route acts as the default child route. It is displayed when none of the other child routes match, such as when the user visits the parent route without specifying anything after its path.
For example, if the parent route is /app and there’s nothing after it (like /app/cities), the index route will show. You can use it to display a default view, like a list of cities or any other content.
Upvotes: 1
Reputation: 159145
In the top example, going to /
would render App
with Home
passed as a child. In the bottom example, going to /
would render App
with neither Home
nor About
being rendered, since neither of their paths match.
For older versions of React Router, more information is available on associated version's Index Routes and Index Links page. Starting in version 4.0, React Router no longer uses the IndexRoute
abstraction to achieve the same goal.
Upvotes: 115