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) {
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.