Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Trigger Modal for React Bootstrap

Sep 15, 2020 • 6 Minute Read

Introduction

React Bootstrap is a pure React implementation of the popular Bootstrap CSS framework. The react-bootstrap library does not use jQuery under the hood, as manipulating DOM directly is considered an anti-pattern in the React ecosystem. Therefore, the jQuery methods to trigger or close a modal aren't going to work. Since React Bootstrap Modal is a React component, you have the flexibility to control the component's behavior using state or hooks.

In this guide, you will learn how to trigger a React Bootstrap Modal programmatically using state.

Set Up The Modal Component

The first step is to import the Modal component from the react-bootstrap library. Along with it, import the Button component that will trigger the modal on click.

      import { Modal, Button } from "react-bootstrap";
    

Once you have imported the component, write the static markup for the modal.

      class App extends Component {
  render() {
    return (
      <Modal>
        <Modal.Header closeButton>
          <Modal.Title>Modal heading</Modal.Title>
        </Modal.Header>
        <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
        <Modal.Footer>
          <Button variant="secondary">Close</Button>
        </Modal.Footer>
      </Modal>
    );
  }
}

export default App;
    

Add The State and Methods

Next, define the state and the methods to close and open the modal.

      class App extends Component {
  state = {
    isOpen: false
  };

  openModal = () => this.setState({ isOpen: true });
  closeModal = () => this.setState({ isOpen: false });

  render() {
    //...
  }
}
    

Add a button inside the render block to trigger the modal.

      class App extends Component {
  // ...
  render() {
    <>
      <div
        className="d-flex align-items-center justify-content-center"
        style={{ height: "100vh" }}
      >
        <Button variant="primary" onClick={this.openModal}>
          Launch demo modal
        </Button>
      </div>
      <Modal>{/* ... */}</Modal>
    </>;
  }
}
    

When the button is clicked, the isOpen state will be set to true. Now, to display the modal, all you need to do is pass the isOpen state value to the show prop of the <Modal /> component.

      <Modal show={this.state.isOpen}>{/* ... */}</Modal>
    

If you check out the result at this point, you'll notice that the modal opens up just fine, but there's no way to close it. So, set the isOpen state to false when the user clicks on the Close button inside the modal. There's also an onHide prop ofthe <Modal /> component that closes the modal when the user clicks on the overlay or presses the Esc button.

      <Modal show={this.state.isOpen} onHide={this.closeModal}>
  <Modal.Header closeButton>
    <Modal.Title>Modal heading</Modal.Title>
  </Modal.Header>
  <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
  <Modal.Footer>
    <Button variant="secondary" onClick={this.closeModal}>
      Close
    </Button>
  </Modal.Footer>
</Modal>
    

Now you should be able to close the modal as well. Pretty easy, right?

Final Component

Take a look at the final component below.

      import React, { Component } from "react";
import { Modal, Button } from "react-bootstrap";

class App extends Component {
  state = {
    isOpen: false
  };

  openModal = () => this.setState({ isOpen: true });
  closeModal = () => this.setState({ isOpen: false });

  render() {
    return (
      <>
        <div
          className="d-flex align-items-center justify-content-center"
          style={{ height: "100vh" }}
        >
          <Button variant="primary" onClick={this.openModal}>
            Launch demo modal
          </Button>
        </div>
        <Modal show={this.state.isOpen} onHide={this.closeModal}>
          <Modal.Header closeButton>
            <Modal.Title>Modal heading</Modal.Title>
          </Modal.Header>
          <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
          <Modal.Footer>
            <Button variant="secondary" onClick={this.closeModal}>
              Close
            </Button>
          </Modal.Footer>
        </Modal>
      </>
    );
  }
}

export default App;
    

Use the useState hook

You can also trigger the modal in a functional component by using the useState hook.

The state and the methods can be declared as follows. The rest is same as the class component, but instead of this.state.isOpen, pass the showModal state variable to the show prop of the <Modal /> component.

      const [showModal, setShow] = useState(false);

const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
    

Check out the complete code below.

      import React, { useState } from "react";
import { Modal, Button } from "react-bootstrap";

function App() {
  const [showModal, setShow] = useState(false);

  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);

  return (
    <>
      <div
        className="d-flex align-items-center justify-content-center"
        style={{ height: "100vh" }}
      >
        <Button variant="primary" onClick={handleShow}>
          Launch demo modal
        </Button>
      </div>
      <Modal show={showModal} onHide={handleClose}>
        <Modal.Header closeButton>
          <Modal.Title>Modal heading</Modal.Title>
        </Modal.Header>
        <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={handleClose}>
            Close
          </Button>
          <Button variant="primary" onClick={handleClose}>
            Save Changes
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}

export default App;
    

Conclusion

You must use controlled components that use the internal state to set the values and change the behavior of a component. Libraries like jQuery do direct DOM manipulation, whereas React components use Virtual DOM to modify the actual DOM on the browser. Using jQuery to change your component's behavior is possible. Still, it will lead to unexpected results and make it difficult to debug. React Bootstrap implements each component in pure React, so you don't have to worry about Bootstrap's dependency on jQuery.

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author