Marco Ferragina Marco Ferragina - 2 months ago 17
React JSX Question

How to get route name in handler using react-route?

As on subject how can I get the route name inside the handler?
For example:

var routes = <Route handler={App} path="/">
<Route name="home" path="/home" handler={HomePage} />
<DefaultRoute handler={HomePage} />
</Route>

Router.run(routes, function(Handler, state) {
var params = state.params;
React.render(<Handler params={params}/>, document.body);
});


Now suppose I have a component like this:

class HomePage extends React.Component {
render() {
return(<div>MyComponent</div>)
}
}


how can I get the current route name? To be more specific I want to get the

name="home"


attribute from

<Route name="home" path="/home" handler={HomePage} />

Answer

Before react-router 0.13 you can use this.getRoutes() using Router.State mixin.

For react-router 0.13 you can use this too:

var currentRoutes = this.context.router.getCurrentRoutes();
var lastRoute = currentRoutes[currentRoutes.length - 1];
console.log(lastRoute.name);

For react-router v2.0.x you can use:

this.props.routes[this.props.routes.length-1]
Comments