stackjlei
stackjlei

Reputation: 10035

What is the purpose of React Router's Index Route in helping your component do stuff like onEnter hooks?

I don't get the docs from React Router below:

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.

What does he mean by routing here? What is onEnter hooks?

Upvotes: 2

Views: 795

Answers (2)

taylorc93
taylorc93

Reputation: 3716

Since App is wrapping other routes, the route that matches the given url is passed to App to be rendered via this.props.children. Because of this, you don't get access to react-router's hooks for Home if you do render Home via a statement such as {this.props.children || <Home/>}. One such hook isonEnter, which fires off a callback whenever a route is entered.

When you define Home as an IndexRoute, it is a distinct route that will match whatever route App matches. This way, we don't need the or clause in App, we can just render the child route via {this.props.children}

Upvotes: 1

Jack
Jack

Reputation: 21193

The docs here are a little more straightforward:

Imagine we'd like to render another component inside of App when the URL is /. Currently, this.props.children inside of App's render method is undefined in this case. We can use an <IndexRoute> to specify a "default" page.

As far as onEnter the docs here are better:

Routes may also define onEnter and onLeave hooks that are invoked once a transition has been confirmed. These hooks are useful for various things like requiring auth when a route is entered and saving stuff to persistent storage before a route unmounts.

Upvotes: 1

Related Questions