Created
June 22, 2020 18:54
-
-
Save paitonic/c91218fcb4155590841c81e5f755d9c0 to your computer and use it in GitHub Desktop.
usePreventBrowserBack.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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