Categories
React Answers

How to intercept or handle browser’s back button in React Router v5?

Spread the love

Sometimes, we want to intercept or handle browser’s back button in React Router v5.

In this article, we’ll look at how to intercept or handle browser’s back button in React Router v5.

How to intercept or handle browser’s back button in React Router v5?

To intercept or handle browser’s back button in React Router v5, we can use the Prompt component.

For instance, we write

<Prompt
  message={(location, action) => {
    if (action === "POP") {
      // ...
    }
    return true;
  }}
/>;

to add the Prompt component with the message prop set to a function that runs when we navigate.

In it, we check if action is 'POP'.

If it is, then we’re navigating with the back button.

Conclusion

To intercept or handle browser’s back button in React Router v5, we can use the Prompt component.

By John Au-Yeung

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

Leave a Reply

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