XAMPPRocky
XAMPPRocky

Reputation: 3619

Prevent popstate event running?

I'm using React, and react router, and I want it so when a user is on certain sections of the website a confirm box shows up, tell them if they left the page they could lose some progress. Currently I have a onbeforeunload event that handles when the user refreshes or closes the window, however with the browser's back button, i have to use onpopstate. using the code shown below the confirm box shows up, but the page still loads to the previous state.

this.currentListener = function(event) {
  if (event.type === 'popstate') {
    event.preventDefault();
    event.stopPropagation();

    var leave =  confirm(message);
    console.log(leave)
  } else {
    return message;
  }
};
window.onbeforeunload = this.currentListener;
window.onhashchange = this.currentListener;

Upvotes: 0

Views: 1695

Answers (1)

BradByte
BradByte

Reputation: 11093

EDIT: converting the component into a mixin. Per React docs, multiple lifecycle calls will result in all being called. http://facebook.github.io/react/docs/reusable-components.html#mixins.

Have you looked at using a static willTransitionFrom method on the component? Something like this...

var PreventLeavingMixin = {
  statics: {
    willTransitionFrom: function(transition, component) {
      //you have access to your component's state and functions with the component param
      if (component.someMethod()) {
        //transition can make the navigation stop
        if (!confirm('Are you sure you want to leave?')) {
          transition.abort();
        }
      }
    }
  }
};

var MyComponent = React.createClass({
  mixins: [PreventLeavingMixin],
  render: function() {
    return: ...
  }
});

Note -- you may need to have to have an onAbort() method specified on the Router.create();

More on Router Transition here: http://rackt.github.io/react-router/#Route Handler

Upvotes: 1

Related Questions