title: Confirm navigation of 'Go Back' in React
body: <p>I have been trying to show users a confirmation popup when the 'back button' is clicked. I am using <code>React Router v3</code>, so I cannot use <code>&lt;Prompt/&gt;</code> of React Router v4.</p>
  
  <p>Here is what I would like to achieve:</p>
  
  <ul>
  <li>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.</li>
  </ul>
  
  <p>I have tried few things:</p>
  
  <p><strong>1) setRouteLeaveHook</strong> (React Router v3) <a href="https://github.com/ReactTraining/react-router/blob/v3/docs/guides/ConfirmingNavigation.md" rel="nofollow noreferrer">React Router v3 doc</a></p>
  
  <pre><code>  componentDidUpdate() {
  
    ...
    if (isDirty)  // denoting that there is unsaved work
      this.props.router.setRouteLeaveHook(
        this.props.route,
        () =&gt; { return 'Unsaved data will be lost' }
      );
    }
  </code></pre>
  
  <ul>
  <li>In this case, I have wrapped my component with <code>withRouter</code> so that I could access <code>this.props.router</code></li>
  <li>I could not achieve my goal as I did the following
  
  <ol>
  <li>Try click 'go back' from <code>www.website.com/about</code> to <code>www.website.com</code></li>
  <li>The popup message shows up, and I click 'No' to stay on the same page</li>
  <li>Although the content (component) is the same, the url is changed back to <code>www.website.com</code></li>
  </ol></li>
  </ul>
  
  <p><strong>2) 'beforeunload' and 'popstate'</strong> </p>
  
  <pre><code>  componentDidUpdate() {
  
    ...
      if (isDirty)  // denoting that there is unsaved work
        window.addEventListener('beforeunload', this.handleBeforeUnload);
        window.addEventListener('popstate', this.handleOnPopState);
      }
    }
  
    handleBeforeUnload = e =&gt; {
      e.preventDefault();
      const msg = 'Are you sure?';
      e.returnValue = msg;
      return msg;
    }
  
    handleOnPopState = e =&gt; {
      e.preventDefault();
      // how can I prevent here?
    }
  </code></pre>
  
  <ul>
  <li>Here, the confirmation message pops up and works as it should be when I try to <code>reload</code>.</li>
  <li>However, no confirmation nor it prevents 'go back' when I click the back button.</li>
  </ul>
  
  <p>What is the best way to prevent accidental navigation from the users?
  Any help or suggestion is appreciated!!</p>
  
  <p>p.s. I cannot upgrade to React Router v4 </p>