0

I'm having trouble in preventing the path from redirecting whenever I click the browser's back button then click the "Cancel" button in the confirmation box.

componentDidMount() {
    window.addEventListener('popstate', this.quit);
}

quit = () => {
    if(confirm('Quit?')) {
        location.assign('/'); // Refreshes the browser then redirects to the homepage
        history.pushState(null, null, null); // Clears the previous history
    } else {
        // What to do if the user clicks "Cancel"?
    }
}

I tried return false but it's still redirecting the app to the homepage (but without refreshing the page). I've tried other solutions like location.pathname = '/currentPathname' and location.replace('/currentPathname'), but since these reload the browser, it displays Cannot get /currentPathname because React Router doesn't need to reload. The <Prompt /> component didn't solve the problem as well because it doesn't have a function prop where I can execute the code above.

jstarnate
  • 319
  • 3
  • 15
  • Try changing the event listener to `beforeunload` instead of `popstate` – Keno Jan 26 '19 at 19:16
  • Worse. No confirmation and refreshing of page happened – jstarnate Jan 26 '19 at 20:47
  • Try the suggestions on this page: https://stackoverflow.com/questions/32841757/detecting-user-leaving-page-with-react-router/37937895 – Keno Jan 27 '19 at 05:40
  • Your best bet to accomplishing your initial goal is to use the `` to prevent unwanted navigation. I'm not sure why you need to execute that specific bit of code, as the browser normally takes care of that. I also created a CodeSandbox with my attempt at it: https://codesandbox.io/s/m3o0wv1w29 – Keno Jan 27 '19 at 05:55
  • Problem solved! `` with the help of `componentDidMount` and `componentWillUnmount` fixed the issue. Thanks guys! – jstarnate Jan 28 '19 at 06:56

1 Answers1

0

Your best bet to accomplishing your initial goal is to use the to prevent unwanted navigation. You may also benefit from using both componentDidMount and componentWillUnmount like so:

componentDidUpdate = () => {
    //Prompt Browser Refresh / Close
    if ("Your Condition" || true) {
      window.onbeforeunload = () => true;
    } else {
      window.onbeforeunload = undefined;
    }
};

componentDidMount() {
    this.setState({ shouldPrompt: true });
    this.props.history.listen((location, action) => {
      console.log(location);
      if (action === "POP") {
      }
    });
}

...

render() {
    return (
        <Prompt
          when={shouldPrompt}
          message="You have unsaved changes, are you sure you want to leave?"
        >
          <Switch>
            <Route path="/" component={Page1} exact />
            <Route path="/page2" component={Page2} exact />
          </Switch>
        </Prompt>
    )
}

Keno
  • 2,018
  • 1
  • 16
  • 26