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.