Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel/Allow react-router transition after confirmation in via dialog box on ComponentWillUnmount

Tags:

reactjs

redux

I'm building a Redux application. I want user to confirmation if they want to leave the Component without saving the data or cancel the transition and save it and maybe then leave.

For example, is there any way to stop a component from unmounting?

like image 458
Raman Choudhary Avatar asked Jul 20 '16 13:07

Raman Choudhary


1 Answers

A better way is to create the following routerWillLeave hook if you are already using react-router.

componentDidMount() {
  this.props.router.setRouteLeaveHook(this.props.route, this.beforeUnload);
}

routerWillLeave(e) {
  // check for a condition here
  if (this.state.allowLeave === false) {
    const message = 'Are you sure?';
    (e || window.event).returnValue = message;
    return message;
  }
}

Also, to make sure this.props.router is available, you must export your component as:

export default withRouter(MyComponent);

See docs at https://github.com/reactjs/react-router/blob/master/docs/guides/ConfirmingNavigation.md.

like image 140
activatedgeek Avatar answered Sep 21 '22 06:09

activatedgeek