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?
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.
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