Home » Reactjs » React-Router : What is the purpose of IndexRoute?

React-Router : What is the purpose of IndexRoute?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I don’t understand what the purpose of using an IndexRoute and IndexLink. It seems that in any case the code below would of 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?

Answers:

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.

Questions:
Answers:

When the user visits, the App component is rendered, but none of the children are, so this.props.children inside of App will be undefined. To render some default UI you could easily do {this.props.children || <Home/>}.

But now Home can’t participate in routing, like the onEnter hooks, etc. You render in the same position as Accounts and Statements, so the router allows you to have Home be a first-class route component with IndexRoute.

<Router>
  <Route path="/" component={App}>
    <IndexRoute component={Home}/>
    <Route path="accounts" component={Accounts}/>
    <Route path="statements" component={Statements}/>
  </Route>
</Router>

Now App can render {this.props.children} and we have a first-class route for Home that can participate in routing.