Tutorial

How To Implement a Modal Component in React

Updated on December 23, 2020
Default avatar

By Cameron Moorehead

How To Implement a Modal Component in React

Introduction

Modals are separate windows within an application, most often as a dialog box. They are a common user interface pattern for providing information or requiring confirmation.

In this tutorial you will learn about how to implement a modal component in your React project. You’ll create a Dashboard component to manage state and a button to access the modal. You’ll also develop a Modal component to build a modal and a button to close. Your project will display and close a modal upon clicking a button.

Prerequisites

To complete this tutorial, you will need:

  • A basic understanding of React before starting this tutorial. You can learn more about React by following the How to Code in React.js series.

Step 1 — Starting the Dashboard Component

The dashboard is where you will display your modal. To begin your dashboard, import an instance of React and the Component object into your Dashboard.js file. Declare a Dashboard component and set your state:

Dashboard.js
import React, { Component } from "react";

class Dashboard extends Component {
  constructor() {
    super();
    this.state = {
      show: false
    };
    this.showModal = this.showModal.bind(this);
    this.hideModal = this.hideModal.bind(this);
  }

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

  hideModal = () => {
    this.setState({ show: false });
  };
}

export default Dashboard

Your state includes the property show with the value of false. This allows you to hide the modal until a user prompts it to open. The functions showModal() updates your state with the .setState() method to change the value of your show property to true when a user opens the modal. Likewise, the .setState() method in your hideModal() function will close the modal and change the value in your show property to false.

Note: Remember to bind your functions on the constructor() using the .bind() method.

Once you’ve applied your state and functions, your render() lifecycle method will handle displaying your modal within the return() statement:

Dashboard.js
import React, { Component } from "react";

class Dashboard extends Component {
  // ...
  render() {
    return (
      <main>
        <h1>React Modal</h1>
        <button type="button" onClick={this.showModal}>
          Open
        </button>
      </main>
    );
  }
}

export default Dashboard

The button accepts the React JSX attribute onClick to apply the .showModal() function and open your modal. You will export your Dashboard component to a higher-order App component connected to your root HTML file.

Step 2 — Building the Modal Component

Create a new file, Modal.js and declare a stateless functional Modal component with three arguments, handleClose, show, and children. The argument show represents the show property on your state:

Modal.js
import './modal.css';

const Modal = ({ handleClose, show, children }) => {
  const showHideClassName = show ? "modal display-block" : "modal display-none";

  return (
    <div className={showHideClassName}>
      <section className="modal-main">
        {children}
        <button type="button" onClick={handleClose}>
          Close
        </button>
      </section>
    </div>
  );
};

Your return() statement passes the argument children, represented as props.children, is a reference to the functionality of opening and closing the modal. The modal also contains a button with a the React JSX onClick attribute that accepts the hideModal() method, here represented as the argument handleClose, passed as props into your Dashboard component.

The variable showHideClassName assigns its value a conditional to check if the value of the show property in your state is true. If so, the modal will appear. Else, the modal will hide. The properties display-block and display-none to show and hide the modal are handled through the modal.css file imported into your Modal component.

Start a new file, modal.css, and set the rules to style the size, color, and shape of your Modal:

modal.css
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width:100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
}

.modal-main {
  position:fixed;
  background: white;
  width: 80%;
  height: auto;
  top:50%;
  left:50%;
  transform: translate(-50%,-50%);
}

.display-block {
  display: block;
}

.display-none {
  display: none;
}

This will produce a centered modal with a white box outline and a shaded background. With your Modal component complete, let’s integrate your component into your Dashboard.

Step 3 — Incorporating the Modal Component

To combine your Modal into your Dashboard, navigate to your Dashboard.js file and import your Modal component below your React insantiation:

Dashboard.js
import React, { Component } from "react";
import Modal from './Modal.js';

class Dashboard extends Component {
  // ...
  render() {
    return (
      <main>
        <h1>React Modal</h1>
        <Modal show={this.state.show} handleClose={this.hideModal}>
          <p>Modal</p>
        </Modal>
        <button type="button" onClick={this.showModal}>
          Open
        </button>
      </main>
    );
  }
}

export default Dashboard

In your return() statement, include your Modal component to display and hide the modal. The attributes show and handleClose are props from your Modal component to manage the logic of your state and the hideModal() function.

Your Dashboard and Modal components will now render on your browser:

Screenshot of open modal component.

Observe how your new Modal component now opens and close.

Conclusion

In this tutorial, you learned how React can be used to implement modals by passing props and functionality from one component to another.

To view this project live, here is a CodePen demo of this project.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Cameron Moorehead

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
5 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

It works, easier than using ReactDOM.createPortal, thank you!

Anywhere in the window whenever I clicked, Modal should disappear! How?

please i want to create different modals on one page using this method but its not working its showing only the last modal that i created

If anyone is getting the error : Failed to compile.

./src/App.js Attempted import error: ‘Modal’ is not exported from ‘./Modal.js’.

it is because you need to do two things.

  1. add an export line to the bottom of Modal.js export {Modal};

2 change the import statement of Dashboard.js it be: import {Modal} from ‘./Modal.js’;

How can I prevent the page underneath the modal from scrolling while the modal is present?

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel