How to open/close react-bootstrap modal programmatically?

Igor Babkin picture Igor Babkin · Apr 6, 2015 · Viewed 75.4k times · Source

I need to open/close modal like

$(element).modal('show')

How to do that?

Answer

Mark picture Mark · Apr 7, 2015

What you are looking for is the custom modal trigger, which uses the OverlayMixin and allows you to manage the modal's state yourself. You can control whether the modal is shown using this.setState({isModalOpen: true}) to achieve the equivalent of what you asked for in your post in the example below. The following code is from the react-bootstrap website (http://react-bootstrap.github.io/components.html#modals):

const CustomModalTrigger = React.createClass({
  mixins: [OverlayMixin],

  getInitialState() {
    return {
      isModalOpen: false
    };
  },

  handleToggle() {
    this.setState({
      isModalOpen: !this.state.isModalOpen
    });
  },

  render() {
    return (
      <Button onClick={this.handleToggle} bsStyle='primary'>Launch</Button>
    );
  },

  // This is called by the `OverlayMixin` when this component
  // is mounted or updated and the return value is appended to the body.
  renderOverlay() {
    if (!this.state.isModalOpen) {
      return <span/>;
    }

    return (
      <Modal bsStyle='primary' title='Modal heading' onRequestHide={this.handleToggle}>
        <div className='modal-body'>
          This modal is controlled by our custom trigger component.
        </div>
        <div className='modal-footer'>
          <Button onClick={this.handleToggle}>Close</Button>
        </div>
      </Modal>
    );
  }
});

React.render(<CustomModalTrigger />, mountNode);

UPDATE (Aug 4, 2015)

In the newest version of React-Bootstrap, whether a modal is shown or not is controlled by a show prop which is passed to the modal. The OverlayMixin is no longer needed to control the modal state. Controlling the state of the modal is still done via setState, in this example via this.setState({ showModal: true }). The following is based off the example on the React-Bootstrap website:

const ControlledModalExample = React.createClass({

  getInitialState(){
    return { showModal: false };
  },

  close(){
    this.setState({ showModal: false });
  },

  open(){
    this.setState({ showModal: true });
  },

  render() {
    return (
      <div>
        <Button onClick={this.open}>
          Launch modal
        </Button>

        <Modal show={this.state.showModal} onHide={this.close}>
          <Modal.Header closeButton>
            <Modal.Title>Modal heading</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <div>Modal content here </div>
          </Modal.Body>
          <Modal.Footer>
            <Button onClick={this.close}>Close</Button>
          </Modal.Footer>
        </Modal>
      </div>
    );
  }
});