Skip to content

Instantly share code, notes, and snippets.

@paitonic
Created June 22, 2020 18:54
Show Gist options
  • Save paitonic/c91218fcb4155590841c81e5f755d9c0 to your computer and use it in GitHub Desktop.
Save paitonic/c91218fcb4155590841c81e5f755d9c0 to your computer and use it in GitHub Desktop.
usePreventBrowserBack.js
// https://medium.com/@subwaymatch/disabling-back-button-in-react-with-react-router-v5-34bb316c99d7
export const usePreventBrowserBack = () => {
const currentPathname = useRef(null);
const currentSearch = useRef(null);
const history = useHistory();
useEffect(() => {
history.listen((newLocation, action) => {
if (action === "PUSH") {
if (
newLocation.pathname !== currentPathname.current ||
newLocation.search !== currentSearch.current
) {
// Save new location
currentPathname.current = newLocation.pathname;
currentSearch.current = newLocation.search;
// Clone location object and push it to history
history.push({
pathname: newLocation.pathname,
search: newLocation.search
});
}
} else {
// Send user back if they try to navigate back
history.go(1);
}
});
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment