Search code examples
react-routernavigation

Prevent navigation with React router v6


I want to popup a modal if a use leaves a form page that tells them their changes will be lost if they leave and they have the option to leave or cancel.

I saw that recent changes to V6 from beta takes out the use of Prompt, useBlocker, and useHistory. I have seen answers for using onBeforeUnload but that seems to only use a built in prompt.

Is there a way to do this with the useNavigate hook?


Solution

  • Here's a similar issue on GitHub https://github.com/remix-run/react-router/issues/8139.

    A possible solution is using UNSAFE_NavigationContext if it exposes block option. See https://github.com/remix-run/react-router/issues/8139#issuecomment-977790637.

    I tested it with "react-router-dom": "^6.0.2" and it works [as a workaround] for now.