Sometimes, we want to intercept and handle browser’s back button in React Router.
In this article, we’ll look at how to intercept and handle browser’s back button in React Router.
How to intercept and handle browser’s back button in React Router?
To intercept and handle browser’s back button in React Router, we can listen for changes in the history
object with the history.listen
method.
For instance, we write
import { useHistory } from "react-router-dom";
const Comp = () => {
const [locationKeys, setLocationKeys] = useState([]);
const history = useHistory();
useEffect(() => {
return history.listen((location) => {
if (history.action === "PUSH") {
setLocationKeys([location.key]);
}
if (history.action === "POP") {
if (locationKeys[1] === location.key) {
setLocationKeys(([_, ...keys]) => keys);
// Handle forward event
} else {
setLocationKeys((keys) => [location.key, ...keys]);
// Handle back event
}
}
});
}, [locationKeys]);
//...
};
to call the useEffect
hook with a callback that calls history.listen
to listen for history
changes.
If history.push
is 'PUSH'
, then we’re going forward.
If it’s 'POP'
, then we used the back button.
In either case, we call setLocationKeys
to update the locationKeys
object.
Conclusion
To intercept and handle browser’s back button in React Router, we can listen for changes in the history
object with the history.listen
method.
3 replies on “How to intercept and handle browser’s back button in React Router?”
How about in v6?
See this page https://thewebdev.info/2022/04/02/how-to-intercept-and-handle-browsers-back-button-in-react-router-v6/
We can use
navigation.listen
instead ofhistory.listen
.When i go back the history.listen. doesn’t work, i need an event when make click in back button but i hope execute the event. before go back, i need show a modal to confirm o cancel, help please