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
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
Well after a long journey to find out how to do that finally i came up with this solution
window.onpopstate = () => {
navigate("/");
}
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>
)
}
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.