I have been trying to show users a confirmation popup when the 'back button' is clicked. I am using React Router v3
, so I cannot use <Prompt/>
of React Router v4.
Here is what I would like to achieve:
I have tried few things:
1) setRouteLeaveHook (React Router v3) React Router v3 doc
componentDidUpdate() {
...
if (isDirty) // denoting that there is unsaved work
this.props.router.setRouteLeaveHook(
this.props.route,
() => { return 'Unsaved data will be lost' }
);
}
withRouter
so that I could access this.props.router
www.website.com/about
to www.website.com
www.website.com
2) 'beforeunload' and 'popstate'
componentDidUpdate() {
...
if (isDirty) // denoting that there is unsaved work
window.addEventListener('beforeunload', this.handleBeforeUnload);
window.addEventListener('popstate', this.handleOnPopState);
}
}
handleBeforeUnload = e => {
e.preventDefault();
const msg = 'Are you sure?';
e.returnValue = msg;
return msg;
}
handleOnPopState = e => {
e.preventDefault();
// how can I prevent here?
}
reload
.What is the best way to prevent accidental navigation from the users? Any help or suggestion is appreciated!!
p.s. I cannot upgrade to React Router v4
If anybody is having the same issue, please refer to my solution here: