Source:  Twitter logo

I have been trying to show users a confirmation popup when the 'back button' is clicked. I am using React Router v3, so I cannot use <Prompt/> of React Router v4.

Here is what I would like to achieve:

  • when a user clicks 'go back' or 'refresh' with unsaved data on a form, the browser shows a confirmation popup 'Yes' and 'No' to either leave or stay.

I have tried few things:

1) setRouteLeaveHook (React Router v3) React Router v3 doc

  componentDidUpdate() {

  ...
  if (isDirty)  // denoting that there is unsaved work
    this.props.router.setRouteLeaveHook(
      this.props.route,
      () => { return 'Unsaved data will be lost' }
    );
  }
  • In this case, I have wrapped my component with withRouter so that I could access this.props.router
  • I could not achieve my goal as I did the following
    1. Try click 'go back' from www.website.com/about to www.website.com
    2. The popup message shows up, and I click 'No' to stay on the same page
    3. Although the content (component) is the same, the url is changed back to www.website.com

2) 'beforeunload' and 'popstate'

  componentDidUpdate() {

  ...
    if (isDirty)  // denoting that there is unsaved work
      window.addEventListener('beforeunload', this.handleBeforeUnload);
      window.addEventListener('popstate', this.handleOnPopState);
    }
  }

  handleBeforeUnload = e => {
    e.preventDefault();
    const msg = 'Are you sure?';
    e.returnValue = msg;
    return msg;
  }

  handleOnPopState = e => {
    e.preventDefault();
    // how can I prevent here?
  }
  • Here, the confirmation message pops up and works as it should be when I try to reload.
  • However, no confirmation nor it prevents 'go back' when I click the back button.

What is the best way to prevent accidental navigation from the users? Any help or suggestion is appreciated!!

p.s. I cannot upgrade to React Router v4

If anybody is having the same issue, please refer to my solution here:

Detecting user leaving page

2 users liked answer #0dislike answer #02
Sang Yun Park profile pic
Sang Yun Park

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).