Categories
React Answers

How to detect user leaving page with React Router?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

3 replies on “How to detect user leaving page with React Router?”

Leave a Reply

Your email address will not be published. Required fields are marked *