How to handle the browser's "back" button in React?
17:10 19 Aug 2022

I have "react-dom-router v6.3.0" (strictly!) now and I couldn't understand how to handle browser's "back" button. For example I need to catch the event, so I could open warning modal that user leaves the page after clicking back. At least give me a direction, please.

I'm using Typescript 4.4.2.

The useBackListener:

import { useEffect, useContext } from "react";
import { NavigationType, UNSAFE_NavigationContext } from "react-router-dom";
import { History, Update } from "history";

const useBackListener = (callback: (...args: any) => void) => {
  const navigator = useContext(UNSAFE_NavigationContext).navigator as History;

  useEffect(() => {
    const listener = ({ location, action }: Update) => {
      console.log("listener", { location, action });
      if (action === NavigationType.Pop) {
        callback({ location, action });
      }
    };

    const unlisten = navigator.listen(listener);
    return unlisten;
  }, [callback, navigator]);
};

Then usage:

  useBackListener(({ location }) => {
    if (isDirty) {
      setOpenWarning(true)
    } else navigate("go back")
  })

How to open modal if form is dirty without redirecting after clicking browser's "back" button ? Also, is it possible to avoid @ts-ignore?

reactjs typescript react-router react-router-dom