Author avatar

Gaurav Singhal

How to Hide a React-Bootstrap Modal Form That Uses Preventdefault()

Gaurav Singhal

  • May 21, 2020
  • 9 Min read
  • 9,532 Views
  • May 21, 2020
  • 9 Min read
  • 9,532 Views
Web Development
Front End Web Development
Client-side Framework
React

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 want 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. This guide will explain how to do 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 react-bootstrap library. You'll need the <Modal />, <Button />, and <Form /> components. Don't forget to import the bootstrap css file to apply the styles.

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

Set up the Modal Component

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

1function App() {
2  return (
3    <div
4      className="d-flex align-items-center justify-content-center"
5      style={{ height: "100vh" }}
6    >
7      <Button variant="primary" onClick={handleShow}>
8        Launch Form modal
9      </Button>
10    </div>
11  );
12}
jsx

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

1function App() {
2  const [show, setShow] = useState(false);
3
4  const handleShow = () => setShow(true);
5
6  return (
7    <div
8      className="d-flex align-items-center justify-content-center"
9      style={{ height: "100vh" }}
10    >
11      <Button variant="primary" onClick={handleShow}>
12        Launch Form modal
13      </Button>
14    </div>
15  );
16}
jsx

Now, add the Modal component after the button.

1function App() {
2  const [show, setShow] = useState(false);
3
4  const handleShow = () => setShow(true);
5
6  return (
7    <>
8      <div
9        className="d-flex align-items-center justify-content-center"
10        style={{ height: "100vh" }}
11      >
12        <Button variant="primary" onClick={handleShow}>
13          Launch Form modal
14        </Button>
15      </div>
16      <Modal show={show}>
17        <Modal.Header closeButton>
18          <Modal.Title>Login Form</Modal.Title>
19        </Modal.Header>
20        <Modal.Body>
21          <></>
22        </Modal.Body>
23        <Modal.Footer>
24          <Button variant="secondary">Close Modal</Button>
25        </Modal.Footer>
26      </Modal>
27    </>
28  );
29}
jsx

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.

1const LoginForm = () => {
2  return (
3    <Form>
4      <Form.Group controlId="formBasicEmail">
5        <Form.Label>Email address</Form.Label>
6        <Form.Control type="email" placeholder="Enter email" />
7      </Form.Group>
8
9      <Form.Group controlId="formBasicPassword">
10        <Form.Label>Password</Form.Label>
11        <Form.Control type="password" placeholder="Password" />
12      </Form.Group>
13      <Form.Group controlId="formBasicCheckbox">
14        <Form.Check type="checkbox" label="Remember Me!" />
15      </Form.Group>
16      <Button variant="primary" type="submit" block>
17        Login
18      </Button>
19    </Form>
20  );
21};
jsx

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.

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

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.

1const LoginForm = ({ onSubmit }) => {
2  const [email, setEmail] = useState("");
3  const [password, setPassword] = useState("");
4  return (
5    <Form onSubmit={onSubmit}>
6      {/*...*/}
7      <Form.Control
8        type="email"
9        placeholder="Enter email"
10        value={email}
11        onChange={(e) => setEmail(e.target.value)}
12      />
13      {/*...*/}
14      {/*...*/}
15      <Form.Control
16        type="password"
17        placeholder="Password"
18        value={password}
19        onChange={(e) => setPassword(e.target.value)}
20      />
21      {/*...*/}
22    </Form>
23  );
24};
jsx

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

1<Modal show={show}>
2  {/* ... */}
3  <Modal.Body>
4    <LoginForm onSubmit={onLoginFormSubmit} />
5  </Modal.Body>
6  {/* ... */}
7</Modal>
jsx

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, i.e., prevent the form submission.

1const onLoginFormSubmit = (e) => {
2  e.preventDefault();
3  // ...
4};
js

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

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

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

1const onLoginFormSubmit = (e) => {
2  e.preventDefault();
3  handleClose();
4};
js

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

1<Modal show={show} onHide={handleClose}>
2  {/* ... */}
3  <Modal.Footer>
4    <Button variant="secondary" onClick={handleClose}>
5      Close Modal
6    </Button>
7  </Modal.Footer>
8</Modal>
jsx

Complete Source Code

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

1import React, { useState } from "react";
2import { Modal, Button, Form } from "react-bootstrap";
3import "./styles.css";
4import "bootstrap/dist/css/bootstrap.css";
5
6const LoginForm = ({ onSubmit }) => {
7  const [email, setEmail] = useState("");
8  const [password, setPassword] = useState("");
9  return (
10    <Form onSubmit={onSubmit}>
11      <Form.Group controlId="formBasicEmail">
12        <Form.Label>Email address</Form.Label>
13        <Form.Control
14          type="email"
15          placeholder="Enter email"
16          value={email}
17          onChange={(e) => setEmail(e.target.value)}
18        />
19      </Form.Group>
20
21      <Form.Group controlId="formBasicPassword">
22        <Form.Label>Password</Form.Label>
23        <Form.Control
24          type="password"
25          placeholder="Password"
26          value={password}
27          onChange={(e) => setPassword(e.target.value)}
28        />
29      </Form.Group>
30      <Form.Group controlId="formBasicCheckbox">
31        <Form.Check type="checkbox" label="Remember Me!" />
32      </Form.Group>
33      <Button variant="primary" type="submit" block>
34        Login
35      </Button>
36    </Form>
37  );
38};
39
40export default function App() {
41  const [show, setShow] = useState(false);
42
43  const handleClose = () => setShow(false);
44  const handleShow = () => setShow(true);
45
46  const onLoginFormSubmit = (e) => {
47    e.preventDefault();
48    handleClose();
49  };
50
51  return (
52    <>
53      <div
54        className="d-flex align-items-center justify-content-center"
55        style={{ height: "100vh" }}
56      >
57        <Button variant="primary" onClick={handleShow}>
58          Launch Form modal
59        </Button>
60      </div>
61      <Modal show={show} onHide={handleClose}>
62        <Modal.Header closeButton>
63          <Modal.Title>Login Form</Modal.Title>
64        </Modal.Header>
65        <Modal.Body>
66          <LoginForm onSubmit={onLoginFormSubmit} />
67        </Modal.Body>
68        <Modal.Footer>
69          <Button variant="secondary" onClick={handleClose}>
70            Close Modal
71          </Button>
72        </Modal.Footer>
73      </Modal>
74    </>
75  );
76}
jsx

Conclusion

That's it from this guide. You can take this learning further, and instead of just closing the modal, you can do other stuff like pass the form values to your server, add tracking functionality, etc. As a JavaScript developer, you have to understand how to use callbacks and plug in additional functionalities instead of default behavior—in this case, closing the modal on form submission.

Keep playing around with the code and exploring the possibilities.