I've am creating a react app and I wanna stop navigation to another page if my form is left dirty
import { useEffect, useState } from "react";
const unsavedChanges = () => {
const [isDirty, setDirty] = useState(false);
useEffect(() => {
function confirmNavigation(event) {
if (isDirty) {
event.preventDefault();
event.returnValue = "Are you sure you want to leave? Your changes will be lost."; // eslint-disable-line no-param-reassign
}
}
window.addEventListener("beforeunload", confirmNavigation);
return () => {
window.removeEventListener("beforeunload", confirmNavigation);
};
}, [isDirty]);
const onDirty = () => setDirty(true);
const onPristine = () => setDirty(false);
return { onDirty, onPristine };
};
export default unsavedChanges;
The code I wrote lets me not reload the page if my form is dirty but I can't prevent it from navigating to another page since react doesn't load the whole page it just loads the data to be changed. I can't use Prompt
, useHistory
, or useBlocking
because they don't exist in react-router v6.4.4.
How can I achieve that?