Skip to content Skip to sidebar Skip to footer

How To Get Current Route In React-router 2.0.0-rc5

I have a router like below: Copy

Solution 2:

You can get the current route using

const currentRoute = this.props.routes[this.props.routes.length - 1];

...which gives you access to the props from the lowest-level active <Route ...> component.

Given...

<Route path="childpath" component={ChildComponent} />

currentRoute.path returns 'childpath' and currentRoute.component returns function _class() { ... }.


Solution 3:

If you use the history,then Router put everything into the location from the history,such as:

this.props.location.pathname;
this.props.location.query;

get it?


Solution 4:

As of version 3.0.0, you can get the current route by calling:

this.context.router.location.pathname

Sample code is below:

var NavLink = React.createClass({
    contextTypes: {
        router: React.PropTypes.object
    },

    render() {   
        return (
            <Link {...this.props}></Link>
        );
    }
});

Solution 5:

For any users having the same issue in 2017, I solved it the following way:

NavBar.contextTypes = {
    router: React.PropTypes.object,
    location: React.PropTypes.object
}

and use it like this:

componentDidMount () {
    console.log(this.context.location.pathname);
}

Post a Comment for "How To Get Current Route In React-router 2.0.0-rc5"