0

Suppose I have a state like below:

this.state = {
      modal: ""
    };

Then I have a button like below:

          <button
                type="button"
                className="btn btn-primary"
                onClick={this.createUser}
                data-dismiss={this.state.modal}
              > Save
          </button>

The create User is like below:

 createUser = () => {
    this.setState({

      modal: "modal"
    });
  };

So when I click the button, I want to close my bootstrap modal defined in the format of data-dismiss button, because I assigned it as modal in createUser.

But its only working in he 2nd click of save button. Why?

Also, how can I change to one click itsself ?

tomerpacific
  • 4,704
  • 13
  • 34
  • 52
Aqib Zaman
  • 265
  • 2
  • 8
  • 17
  • Can you pls. have a look on this post? https://stackoverflow.com/questions/38537651/bootstrap-close-modal-not-working – gazdagergo Jan 29 '19 at 08:25

1 Answers1

0

Setting data-dismiss to modal won't close the modal itself. The second click trigger bootstrap.js and close the modal.

I think you'd want to get a ref to your modal, then close it with jQuery on click. Something like

// in your constructor
this.modalRef = React.createRef();


// class method
clickHandler() {
  this.createUser();
  $(this.ref.current).modal('hide');
}

// render function
return (
  <div id="modal" ref={this.modalRef}>
    ...
  </div>
)

If you're using a lot of bootstrap modal though, perhaps you may consider using reactstrap, which has convenient built-in props to control modal.

Derek Nguyen
  • 11,294
  • 1
  • 40
  • 64