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.