I know many questions about this have already been asked but I'm struggling finding what I need. I am using react-router 5.1.2 to manage navigation in my web-app. I want to alert the user before he leaves the page. Attach beforeUnload listener does not work when users press the browser's back button. I understand I can use history.block() or <Prompt>, but the alert does not behaves like the default one shown when beforeUnload is fired, e.g. I can press back button twice then press "cancel" and have inconsistencies between the route and the actual rendered component. The question is: how can I alert the user pressing back button obtaining a confirmation dialog that behaves as the default one (preventing further actions other than those proposed by the alert)?
This is the custom hook I've used so far:
const alertUser = (e: BeforeUnloadEvent | PopStateEvent) => {
e.preventDefault();
e.returnValue = '';
};
export const useAlertBeforeLeaving = (showAlert = true) => {
const history = useHistory();
const unblock = useRef<UnregisterCallback | null>(null);
useEffect(() => {
if (showAlert) {
window.addEventListener('beforeunload', alertUser);
unblock.current = history.block('Leave the page?');
}
return () => {
if (showAlert && unblock.current) {
window.removeEventListener('beforeunload', alertUser);
unblock.current();
}
};
}, [history, showAlert]);
};