Cancel / Allow transition with the router after confirmation through the ComponentWillUnmount dialog box

I am creating a Redux application. I want the user to receive confirmation if they want to leave the Component without saving the data or canceling the transition, and save it, or maybe it will leave.

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

+4
source share
2 answers

It is best to create the following routerWillLeavehook 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;
  }
}

In addition, to make sure that it this.props.routeris available, you must export your component as:

export default withRouter(MyComponent);

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

+5

. window.onbeforeunload, componentWillUnmount. .

window.onbeforeunload -, undefined, .

window.onbeforeunload = () => 'Are you sure?';
+1

Source: https://habr.com/ru/post/1648512/


All Articles