In React Router v6, how to check form is dirty before leaving page/route

Update:

Prompt, usePrompt and useBlocker have been removed from react-router-dom. This answer will not currently work, though this might change. The github issue, opened Oct 2021, is here

The answer…

This answer uses router v6.

  1. You can use usePrompt.
  • usePrompt will show the confirm modal/popup when you go to another route i.e. on mount.
  • A generic alert with message when you try to close the browser. It handles beforeunload internally
usePrompt("Hello from usePrompt -- Are you sure you want to leave?", isBlocking);
  1. You can use useBlocker
  • useBlocker will simply block user when attempting to navigating away i.e. on unmount
  • A generic alert with message when you try to close the browser. It handles beforeunload internally
useBlocker(
    () => "Hello from useBlocker -- are you sure you want to leave?",
    isBlocking
  );

Demo for both 1 & 2

  1. You can also use beforeunload. But you have to do your own logic. See an example here

Leave a Comment