1

I Want to show modal popup in spfx react webpart. Below is the code I am using:

<div>
   <button onClick={e => this._OpenModal(this)}>Open Modal</button>
   <div id="myModal" className="modal">
      <div className="modal-content">
          <span className="close" onClick={e => this._CloseModal(this)}>&times;</span>
          <p>Some text in the Modal..</p>
      </div>
   </div>
</div>

private _OpenModal = (e): void => {
    e.style.display = "block";
    // tslint:disable-next-line:semicolon
};

private _CloseModal = (e): void => {
    e.style.display = "none";
    // tslint:disable-next-line:semicolon
};

But I am unable to fire style.display.

Please guide ne how to fire the event?

Error :

TypeError: Cannot set property 'display' of undefined at ShopingCart._this._OpenModal

1

Here's how I would do this:

  1. Add a boolean variable in your state (e.g.: isLoaded or showDialog). Let's use showDialog
  2. In your render code, use conditional rendering to render the dialog. E.g.:
{this.state.showDialog && <div id="myModal" className="modal">
      <div className="modal-content">
          <span className="close" onClick={e => this._CloseModal(this)}>&times;</span>
          <p>Some text in the Modal..</p>
      </div>
   </div>}
  1. Change your _ShowModal and _CloseModal code to change the state, as follows:
private _OpenModal = (e): void => {
    this.setState({
       showDialog: true
    });
}

private _CloseModal = (e): void => {
    this.setState({
       showDialog: false
    });
}

It should work for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.