I am currently using "react-router": "^2.4.0"
on my chat application and confused on how to redirect when there is no user. I don't think redirect works in "^2.4.0"
.
Should I use onEnter
hooks on my chat path?
Something like this:
<Route path="chat" component={Chat} onEnter={Chat.willTransitionTo}/>
routes.js
<Route path="/" component={App} >
<IndexRoute component={Chat} />
<Route path="chat" component={Chat} />
<Route path="login" component={Login} />
</Route>
Chat.jsx
static willTransitionTo(transition){
var state = ChatStore.getState();
if(!state.user){
transition.redirect('/login');
}
}
I made it work by using setRouteLeaveHook
as it says here:
https://github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md
return false to prevent a transition w/o prompting the user
However, they forget to mention that the hook should be unregistered as well, see here and here.
We can use this to implement our own solution as follows:
class YourComponent extends Component {
constructor() {
super();
const {route} = this.props;
const {router} = this.context;
this.unregisterLeaveHook = router.setRouteLeaveHook(
route,
this.routerWillLeave.bind(this)
);
}
componentWillUnmount() {
this.unregisterLeaveHook();
}
routerWillLeave() {
// return false to prevent a transition w/o prompting the user,
// or return a string to allow the user to decide:
if (!this.state.isSaved) {
return 'Your work is not saved! Are you sure you want to leave?'
}
}
...
}
YourComponent.contextTypes = {
router: routerShape
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With