Block Navigation
const [isChangesMade, setIsChangesMade] = useState(false);
const blocker = useBlocker(isChangesMade)
useEffect(() => {
if (blocker.state === 'blocked' && isChangesMade) {
setCustomDisplayModal(true);
}
if (blocker.state === 'blocked' && !isChangesMade) {
blocker.reset?.();
}
//return () => blocker.reset?.();
}, [blocker, isChangesMade]);
The "isChangedMade" can be replaced with any type of conditional, either from an expression, redux state, etc
The useEffect monitors when to trigger the block mechanism. The setCustomDisplayModal is then used to display a modal (Custom Component) to prevent clicking away from the page.
Hard Refresh
The blocker is not enough to prevent the hard refresh from occuring, to handle this scenario, you need the beforeunload event to display a default browser message about the unsaved changes.
useEffect(() => {
if (!isChangesMade) return;
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
event.preventDefault();
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, [isChangesMade]);
react-router
/react-router-dom
doesn't have this functionality. Could you provide a minimal and complete code example of the Vue code, and your attempt at something similar in React we can help? – Blunt