0

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?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Ghayas Ud Din
  • 315
  • 2
  • 14
  • None of `Prompt`, `useHistory`, and `useBlocking` exist in ***any*** version of RRDv6. Does this answer your question? https://stackoverflow.com/a/74065505/8690857 It works through RRDv6.8.1. – Drew Reese Feb 19 '23 at 20:02
  • Its importing `Router` like `import { unstable_HistoryRouter as Router } from "react-router-dom";` But I'm using createBrowserRouter `const router = createBrowserRouter(createRoutesFromElements(route));` `function App() { return ; } ` How can i use history here – Ghayas Ud Din Feb 20 '23 at 12:09
  • That's one of the caveats with the later RRDv6 versions. The RRD maintainers are moving away from exposing the history object, making it more difficult to implement features that are considered poor UI/UX, just like the browsers have done. Are you *actually* using any of the Data APIs the new routers provide/enable? Can you [edit] the post to include a more complete [mcve] of the code you are working with? It's better to just run some logic (to save, or not, whatever) prior to the component unmounting or the page unloading than trying to block the UI to "confirm" with a user. – Drew Reese Feb 20 '23 at 18:03

0 Answers0