0

I've been looking for this question and found it but they're using class components and react router dom v5

What i want is When user click browser back button I'll redirect them to home page

Drew Reese
  • 103,803
  • 12
  • 69
  • 96
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Mar 07 '22 at 03:40

3 Answers3

1

Well after a long journey to find out how to do that finally i came up with this solution

window.onpopstate = () => {
  navigate("/");
}
0

About how to detect your user's click to the back button, I found this answer.

About navigating them to the home page, in react-router-dom v6 you can do that using the useNavigate hook.

Here's an example:

import { useNavigate } from 'react-router-dom'

const myComponent = () => {
  const navigate = useNavigate()

  return (
    <button onClick={() => navigate('/')}>Back to Home Page</button>
  )
}
Dharman
  • 26,923
  • 21
  • 73
  • 125
0

If you are simply wanting to run a function when a back navigation (POP action) occurs then a possible solution is to create a custom hook for it using the exported NavigationContext.

Example:

import { UNSAFE_NavigationContext } from "react-router-dom";

const useBackListener = (callback) => {
  const navigator = useContext(UNSAFE_NavigationContext).navigator;

  useEffect(() => {
    const listener = ({ location, action }) => {
      console.log("listener", { location, action });
      if (action === "POP") {
        callback({ location, action });
      }
    };

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

Usage:

import { useNavigate } from 'react-router-dom';
import { useBackListener } from '../path/to/useBackListener';

...

const navigate = useNavigate();

useBackListener(({ location }) =>
  console.log("Navigated Back", { location });
  navigate("/", { replace: true });
);

If using the UNSAFE_NavigationContext context is something you'd prefer to avoid then the alternative is to create a custom route that can use a custom history object (i.e. from createBrowserHistory) and use the normal history.listen. See my answer here for details.

Drew Reese
  • 103,803
  • 12
  • 69
  • 96