Catch navigation events in SPFX webpart

Iron Contributor

Hi,

I have a spfx webpart written in react that I am using on a classic sharepoint editform. I want to prompt the user to save changes if he tries to navigate away from the page.

 

I tried putting logic in the componentWillUnmount method of my react class, but it does not get called when the user navigates away.

 

How can I handle this requirement in a react webpart?

1 Reply

Ah, I found it. I put this in my webpart render

Ah, I found it. I put this in my webpart render method:
 this.reactElement = React.createElement(TrForm, formProps);
      var formComponent: TrForm = ReactDom.render(this.reactElement, this.domElement) as TrForm;//render the component
      window.onbeforeunload = function (e) {
        debugger;

        if (formComponent.state.isDirty) {
          var dialogText = "You have unsaved changes, are you sure you want to leave?"
          e.returnValue = dialogText;
          return dialogText;

        }
      }