How do I disable a browser back button click from user using react-router-dom
v4?
I am showing a modal on a page and when the user presses browser back button then the user is taken to the previous screen, instead I want to simply close the modal.
I tried doing this
onBackButtonEvent(event) {
event.preventDefault();
// the user shouldn't be able to move backward or forward
}
componentDidMount() {
window.onpopstate = this.onBackButtonEvent;
}
But this doesn't prevent the user from going backward or forward. Is there a way to handle this via react-router-dom
?
I have tried multiple solutions but nothing seems to work.
Intercept or Handle the Browser's Back Button in React Router. We can listen to back button actions by running the setRouteLeaveHook event for back button actions. } export default withRouter(App);
To go back to the previous page with React router: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function passing it -1 - navigate(-1) . Calling navigate with -1 is the same as hitting the back button.
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 }); );
Going back Sometimes you'll want to be able to programmatically trigger this behavior, and for that you can use navigation.goBack(); . On Android, React Navigation hooks in to the hardware back button and fires the goBack() function for you when the user presses it, so it behaves as the user would expect.
I know this question's a little old but I stumbled on it while looking for the answer myself. There's no clean way to "disable" the back button but to enable the user to only close the modal when clicking the browser back button I found this to work.
Simply pass the history to your modal component in props and call the below on the componentWillUnmount
function.
componentWillUnmount() {
this.props.history.goForward();
}
This will seamlessly force the browser to stay on the same page but close the modal (assuming it's a class component).
UPDATE: If using functional components, the above componentWillUnmount function looks like the hook below.
React.useEffect(() => {
return () => {
props.history.goForward();
}
}, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With