How to prevent unmounting of React components?

I am trying to implement a function in my application, when a user tries to navigate from an unregistered form, they are given a confirmation that asks them if they are sure they want to leave before saving their changes.

The componentWillUnmount method seems like a perfect candidate for this, as it fires for all the different ways the user can abandon the form (changes the state of the parent component which makes it disappear, navigates to a different route, etc.). However ... I have no way to prevent unmounting when the assertion returns false.

Any suggestions on how I can implement this?

+3


source to share


2 answers


This is best handled through a router agent: setRouteLeaveHook.

componentWillMount() {
    this.unregisterLeaveHook = props.router.setRouteLeaveHook(props.route, this.routerWillLeave.bind(this));
}

routerWillLeave(nextLocation) {
  return false;        
}

      



And when the component is unmounted, unregister:

componentWillUnmount() {
    this.unregisterLeaveHook();
}

      

+5


source


I would not recommend doing this in componentWillUnmount. I usually want to do this in a store (if you are using flux architecture). Usually the store has to keep track of all data. The componentWillUnmount function is that you would like to disable the store listener.



0


source







All Articles