Skip to content

Contact sales

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

How to Open and Close a React-Bootstrap Modal Programmatically

May 18, 2020 • 10 Minute Read

Introduction

React Bootstrap is an excellent library that gives you the flexibility of writing your code on top of the react-bootstrap component API. The components have many props that can be used to extend the default functionalities and allow you to bind your application logic into it.

For example, let's say you have to add a piece of code that tracks users' behavior when they interact with a modal. You can use the show and onHide props to display and run a callback when the modal is hidden. In this guide, you'll be doing something very simple and straightforward: you'll hide the modal when the form inside of it is submitted.

Import Components from React Bootstrap

The first step is to import all the relevant components from the react-bootstrap library. You will require the <Modal />, <Button />, and <Form /> components. Don't forget to import the bootstrap css file to apply the styles.

      import React from "react";
import { Modal, Button, Form } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.css";
    

Set up the Modal Component

Inside the App component, add a button that will open up the modal.

      function App() {
  return (
    <div
      className="d-flex align-items-center justify-content-center"
      style={{ height: "100vh" }}
    >
      <Button variant="primary" onClick={handleShow}>
        Launch Form modal
      </Button>
    </div>
  );
}
    

In the handleShow() function, set a Boolean state value to true and use it to display or trigger the modal.

      function App() {
  const [show, setShow] = useState(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 Form modal
      </Button>
    </div>
  );
}
    

Now, add the Modal component after the button.

      function App() {
  const [show, setShow] = useState(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 Form modal
        </Button>
      </div>
      <Modal show={show}>
        <Modal.Header closeButton>
          <Modal.Title>Login Form</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <></>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary">Close Modal</Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}
    

Pass the show state variable to the show prop of the Modal component to control the modal behavior. In the handleClose() function, set the show state to false to close the modal.

Build the Login Form

For this demo, you'll be creating a login form. So, create a <LoginForm /> component and call it inside the modal body.

      const LoginForm = () => {
  return (
    <Form>
      <Form.Group controlId="formBasicEmail">
        <Form.Label>Email address</Form.Label>
        <Form.Control type="email" placeholder="Enter email" />
      </Form.Group>

      <Form.Group controlId="formBasicPassword">
        <Form.Label>Password</Form.Label>
        <Form.Control type="password" placeholder="Password" />
      </Form.Group>
      <Form.Group controlId="formBasicCheckbox">
        <Form.Check type="checkbox" label="Remember Me!" />
      </Form.Group>
      <Button variant="primary" type="submit" block>
        Login
      </Button>
    </Form>
  );
};
    

The <LoginForm /> component also needs to accept a callback prop that will be executed when the form is submitted, so that it can set the show state variable to false in the <App /> component.

      const LoginForm = ({ onSubmit }) => {
  return <Form onSubmit={onSubmit}>{/* ... */}</Form>;
};
    

Using the useState hook, create the email and password state variables to control the form values, and then pass the variables to the value prop of the respective <Form.Control /> component.

      const LoginForm = ({ onSubmit }) => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  return (
    <Form onSubmit={onSubmit}>
      {/*...*/}
      <Form.Control
        type="email"
        placeholder="Enter email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      {/*...*/}
      {/*...*/}
      <Form.Control
        type="password"
        placeholder="Password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      {/*...*/}
    </Form>
  );
};
    

Once the <LoginForm /> component is ready, render it inside the <Modal.Body /> component.

      <Modal show={show}>
  {/* ... */}
  <Modal.Body>
    <LoginForm onSubmit={onLoginFormSubmit} />
  </Modal.Body>
  {/* ... */}
</Modal>
    

Handle the onSubmit() Action

As you can see above, the onLoginFormSubmit function reference is passed to the onSubmit prop of the LoginForm component. So in the onLoginFormSubmit function, the very first line will prevent the default behavior—that is, the form submission.

      const onLoginFormSubmit = (e) => {
  e.preventDefault();
  // ...
};
    

Now, instead of form submission, you need to close the modal. Create another helper function, handleClose, similar to the handleShow function, but instead of setting the show state variable to true, the handleClose function will set the show variable to false.

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

To close the modal, simply call the handleClose() function inside the onLoginFormSubmit() function body.

      const onLoginFormSubmit = (e) => {
  e.preventDefault();
  handleClose();
};
    

There you go! Now, there are still a couple of places you need to use the handleClose function in the Modal component.

      <Modal show={show} onHide={handleClose}>
  {/* ... */}
  <Modal.Footer>
    <Button variant="secondary" onClick={handleClose}>
      Close Modal
    </Button>
  </Modal.Footer>
</Modal>
    

Complete Source Code

In this section, you can find the entire source code for your reference.

      import React, { useState } from "react";
import { Modal, Button, Form } from "react-bootstrap";
import "./styles.css";
import "bootstrap/dist/css/bootstrap.css";

const LoginForm = ({ onSubmit }) => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  return (
    <Form onSubmit={onSubmit}>
      <Form.Group controlId="formBasicEmail">
        <Form.Label>Email address</Form.Label>
        <Form.Control
          type="email"
          placeholder="Enter email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
      </Form.Group>

      <Form.Group controlId="formBasicPassword">
        <Form.Label>Password</Form.Label>
        <Form.Control
          type="password"
          placeholder="Password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
      </Form.Group>
      <Form.Group controlId="formBasicCheckbox">
        <Form.Check type="checkbox" label="Remember Me!" />
      </Form.Group>
      <Button variant="primary" type="submit" block>
        Login
      </Button>
    </Form>
  );
};

export default function App() {
  const [show, setShow] = useState(false);

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

  const onLoginFormSubmit = (e) => {
    e.preventDefault();
    handleClose();
  };

  return (
    <>
      <div
        className="d-flex align-items-center justify-content-center"
        style={{ height: "100vh" }}
      >
        <Button variant="primary" onClick={handleShow}>
          Launch Form modal
        </Button>
      </div>
      <Modal show={show} onHide={handleClose}>
        <Modal.Header closeButton>
          <Modal.Title>Login Form</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <LoginForm onSubmit={onLoginFormSubmit} />
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={handleClose}>
            Close Modal
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}
    

Conclusion

That's it from this guide. You can take this learning further: Instead of just closing the modal, you can do other kinds of stuff like passing the form values to your server, adding tracking functionality, etc. As a JavaScript developer, you should understand how to use callbacks and how you can plug in additional functionalities to replace default behavior. In this case, you closed the modal on form submission.

Keep playing around with the code and explore more possibilities.

Learn More

Explore these React and Bootstrap courses from Pluralsight to continue learning: