I have a router like below:
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Index}/>
<Route path="login" component={Login}/>
</Route>
</Router>
Here's what I want to achieve :
/login
if not logged in/login
when they are already logged in, redirect them to root /
so now I'm trying to check user's state in App
's componentDidMount
, then do something like:
if (!user.isLoggedIn) {
this.context.router.push('login')
} else if(currentRoute == 'login') {
this.context.router.push('/')
}
The problem here is I can't find the API to get current route.
I found this closed issue suggested using Router.ActiveState mixin and route handlers, but it looks like these two solutions are now deprecated.
This question is related to
javascript
reactjs
react-router
You could use the 'isActive' prop like so:
const { router } = this.context;
if (router.isActive('/login')) {
router.push('/');
}
isActive will return a true or false.
Tested with react-router 2.7
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>
);
}
});
In App.js
add the below code and try
window.location.pathname
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?
Try grabbing the path using:
document.location.pathname
In Javascript you can the current URL in parts. Check out: https://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
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() { ... }
.
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);
}
Works for me in the same way:
...
<MyComponent {...this.props}>
<Route path="path1" name="pname1" component="FirstPath">
...
</MyComponent>
...
And then, I can access "this.props.location.pathname" in the MyComponent function.
I forgot that it was I am...))) Following link describes more for make navigation bar etc.: react router this.props.location
Source: Stackoverflow.com