Author avatar

Gaurav Singhal

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

Gaurav Singhal

  • May 21, 2020
  • 9 Min read
  • 75 Views
  • May 21, 2020
  • 9 Min read
  • 75 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.

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

Set up the Modal Component

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

1
2
3
4
5
6
7
8
9
10
11
12
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>
  );
}
jsx

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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>
  );
}
jsx

Now, add the Modal component after the button.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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>
    </>
  );
}
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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>
  );
};
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.

1
2
3
const LoginForm = ({ onSubmit }) => {
  return <Form onSubmit={onSubmit}>{/* ... */}</Form>;
};
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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>
  );
};
jsx

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

1
2
3
4
5
6
7
<Modal show={show}>
  {/* ... */}
  <Modal.Body>
    <LoginForm onSubmit={onLoginFormSubmit} />
  </Modal.Body>
  {/* ... */}
</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.

1
2
3
4
const onLoginFormSubmit = (e) => {
  e.preventDefault();
  // ...
};
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.

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

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

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

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

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

Complete Source Code

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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>
    </>
  );
}
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.

0