Home > database >  How to handle the browser's "back" button in React?
How to handle the browser's "back" button in React?

Time:08-20

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 { useContext, useEffect } from 'react'
import { UNSAFE_NavigationContext } from 'react-router-dom'

// @ts-ignore
export const useBackListener = callback => {
  const { navigator } = useContext(UNSAFE_NavigationContext)

  useEffect(() => {
    // @ts-ignore
    const listener = ({ location, action }) => {
      console.log('listener', { location, action })
      if (action === 'POP') {
        callback({ location, action })
      }
    }
    // @ts-ignore
    const unlisten = navigator.listen(listener)
    return unlisten
  }, [callback, navigator])
}

Then usage:

  // @ts-ignore
  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?

CodePudding user response:

You can create your own Custom Router with history object which will help you to listen actions such as "POP" for react-router-dom v6.

To create custom route you may want to follow these steps: https://stackoverflow.com/a/70646548/13943685

CodePudding user response:

This how React Router specific history object comes into play. It provides a way to "listen for URL" changes whether the history action is push, pop, or replace

 let history = createBrowserHistory();
history.listen(({ location, action }) => {
  // this is called whenever new locations come in
  // the action is POP, PUSH, or REPLACE
});

OR you can also use

window.addEventListener("popstate", () => {
  // URL changed!
});

But that only fires when the user clicks the back or forward buttons. There is no event for when the programmer called window.history.pushState or window.history.replaceState.

  • Related