Categories
React Answers

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

Spread the love

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.

By John Au-Yeung

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

3 replies on “How to intercept and handle browser’s back button in React Router?”

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

Leave a Reply

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