2
votes

I am navigating from one page to another using history.push which is available from below

import { withRouter } from 'react-router-dom

I am able to navigate properly but i have a requirement that if i move from Page A to Page B, i should not be allowed to go back to previous page using Browser back button.

I know this can be achieved by window.redirect but i dont want to use that. The problem with that is the entire state and redux store information is lost. Does anyone know if i can use withRouter and still be able to achieve the requirement above.

1
You can use browserHistory.replace instead of browserHistory.push to remove A from browsing history. That way if user goes to B, he won't be able to go to A, instead go to a URL previous of A. - Kanishk Anand

1 Answers

2
votes

You could use the history.replace('/Whatever_screen') to replace the current page in the stack.

replace(path, [state]) - (function) Replaces the current entry on the history stack.

Second option:

You could use the below code to block the user to going back in the history.

 componentDidMount() {
    const { history } = this.props;
    window.onpopstate = function (event) {
      history.go(1);
    };
  }

Working Example:

Edit react-disable-back-button-v1 (forked)

MDN reference here:

There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the location.replace() method, which replaces the current item of the session history with the provided URL.