Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router Dom v4 handle browser back button

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.

like image 631
Singh Avatar asked Jul 17 '18 12:07

Singh


People also ask

How do you handle back button of browser in react?

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);

How do you go back in dom react router?

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.

How do you handle the browser Back button in react v6 router?

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 }); );

How do I go back on button click in react JS?

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.


1 Answers

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();
        }
    }, []);
like image 60
James Morrison Avatar answered Sep 27 '22 19:09

James Morrison