How to detect user leaving page with React Router?

Sometimes, we want to detect user leaving page with React Router.

In this article, we’ll look at how to detect user leaving page with React Router.

How to detect user leaving page with React Router?

To detect user leaving page with React Router, we can use the Prompt component.

For instance, we write

import { Prompt } from "react-router";

const MyComponent = () => (
  <>
    <Prompt
      when={shouldBlockNavigation}
      message="Are you sure you want to leave the page?"
    />
    {/* Component JSX */}
  </>
);

to add the Prompt component to MyComponent that lets us show a message when we’re leaving the page.

And we set the when prop to shouldBlockNavigation so the prompt is only shown when shouldBlockNavigation is true and when we’re leaving the page.

Conclusion

To detect user leaving page with React Router, we can use the Prompt component.