(With help of ChatGPT) I developed code that prevents not intended browser tab close when the user is in a certain route of my React app with BrowserRouter
:
import { useEffect } from "react";
export const useBlockTabClose = () => {
useEffect(() => {
const handleBeforeUnload = (event) => {
const message = 'You have unsaved changes. Are you sure you want to leave?';
event.returnValue = message;
return message;
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, []);
};
However, this does not prevent clicking a menu item and navigating away from the BrowserRouter page with a form, so losing the form data. Please, explain how to also prevent navigating away.