DEV Community

Maylene Poulsen
Maylene Poulsen

Posted on

Using a Modal in React

For my final project at Flatiron, I built an app that allowed users to fill out forms and submit information on different pages. Because I didn't want to keep rendering an entire page with a form and then going back to the previous page to display the information, I decided to use a modal. A modal is just a design term for a pop-up form that appears when a user clicks on a button. I also used some of react bootstrap to style and render the modal.

To get the modal to display a showModal state can be set in the parent component.

state = {
  showModal: false,
}

Also in needed in the parent component are two methods to change the state of the modal. One method to set the showModal state to true when a button is clicked, and another method to set the showModal state back to false when the user clicks the x in the corner.

 closeModal = () => {
    this.setState({ showModal: false });
  };

  openModal = () => {
    this.setState({ showModal: true });
  };

Next you will create a button with an onClick event handler that will call the openModal method and set the state to true. The component that is being rendered as a modal should open on the page of the parent component. The modal component itself will need the state of the modal as well as the closeModal method passed to it in props. Any other props that modal component needs should be passed to it as well.

In the component that I wanted to render as a modal, I imported from react-bootstrap.

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

Then in the modal component, I wrote the form to show in a method called renderAddGift.

renderAddGift = () => {
  return (
  ...all the form labels and inputs...
  )
}

In the render method of the modal component, I used the Modal wrapper imported from react-bootstrap to render the above form depending on the state of the modal.

 render() {
    return (
      <div>
        <Modal show={this.props.showModal} onHide={this.props.closeModal}>
          <Modal.Header closeButton={true} style={{ color: "#3e6b89" }}>
            <h3>Add A Gift Idea</h3>
          </Modal.Header>
          {this.renderAddGift()}
        </Modal>
      </div>
    );
  }
}

I found this to be an easy beginners approach to set up a working modal and understand how it was rendering to my page. It also made the page it was rendering on cleaner with only necessary information displayed. A common place to use modals is on the login and sign-up on a home page.

Top comments (1)

Collapse
 
lukidwianto profile image
Luki

Its more simple if you just use one function to close and open modal:

toggleModal = () => {
this.setState({ showModal: !this.state.showModal });
};