Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting willTransitionTo in react-router 2.4.0?

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');
  }
}
like image 290
Raghib Hasan Avatar asked Oct 30 '22 04:10

Raghib Hasan


1 Answers

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
};
like image 51
mlunoe Avatar answered Nov 09 '22 15:11

mlunoe