How to Create a Modal in React

Share with a friend:

Modals are a common user interface component used in web applications to display content in a layered, temporary window that overlays the main content. Modals are often used to show additional information, gather user input, or confirm actions. In this tutorial, we will learn how to create a custom modal component in React. Visit here for an in-depth guide on React.

If you are not interested in creating a modal from scratch, visit this article on React UI libraries with multiple useful pre-built components.

Table of Contents

Prerequisites

Before we begin, make sure you have the following:

  • Basic knowledge of React and JavaScript.
  • Node.js installed on your machine.
  • A code editor of your choice.

Setting Up the Project

If you already have your project setup you may skip this section.

To create a modal in React, we will start by setting up a new React project. Open your terminal and follow these steps:

  1. Create a new directory for your project: mkdir react-modal-example.
  2. Navigate to the project directory: cd react-modal-example.
  3. Initialize a new React project: npx create-react-app

Once the project is set up, open it in your code editor.

Creating the Modal Component

In React, we can create reusable components to encapsulate and manage the behavior of the modal. Let’s create a new file called Modal.js in the src directory and define our modal component:

import React from 'react';

const Modal = ({ isOpen, onClose, children }) => {
  if (!isOpen) {
    return null;
  }

  return (
    <div className="modal">
      <div className="modal-content">
        {children}
        <button className="modal-close" onClick={onClose}>
          Close
        </button>
      </div>
    </div>
  );
};

export default Modal;

In the above code, we define a functional component called Modal. It accepts three props:

  • isOpen – a boolean indicating whether the modal should be open or closed.
  • onClose – a function to be called when the modal is closed.
  • children – the content to be rendered inside the modal.

We check the value of isOpen and return null if it’s false, indicating that the modal should be hidden. Otherwise, we render the modal with the provided children and a close button that triggers the onClose function.

Using createPortal()

React’s createPortal() method provides a way to render a component’s content into a different DOM element outside of its parent hierarchy. This feature is particularly useful when creating a modal in React, as it allows us to render the modal content directly into the root of the HTML document, ensuring that the modal appears on top of all other elements.

To utilize createPortal() for our modal implementation, we need to make a few adjustments to our existing code. Let’s modify the Modal.js component as follows:

import React from 'react';
import ReactDOM from 'react-dom';

const Modal = ({ isOpen, onClose, children }) => {
  if (!isOpen) {
    return null;
  }

  return ReactDOM.createPortal(
    <div className="modal">
      <div className="modal-content">
        {children}
        <button className="modal-close" onClick={onClose}>
          Close
        </button>
      </div>
    </div>,
    document.body
  );
};

export default Modal;

In the updated code, we import ReactDOM alongside React to access the createPortal() method. Instead of directly returning the JSX for the modal component, we use createPortal() and provide it with two arguments: the modal JSX and the target DOM element where the modal should be rendered (in this case it was the body element).

Implementing the Modal in App Component

Now that we have our Modal component, let’s integrate it into our App component. Open the src/App.js file and modify it as follows:

import React, { useState } from 'react';
import Modal from './Modal';

const App = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const openModal = () => {
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
  };

  return (
    <div>
      <h1>React Modal Example</h1>
      <button onClick={openModal}>Open Modal</button>
      <Modal isOpen={isModalOpen} onClose={closeModal}>
        <h2>Welcome to the Modal</h2>
        <p>This is the content of the modal.</p>
      </Modal>
    </div>
  );
};

export default App;

In the above code, we import the Modal component and create a new state variable isModalOpen using the useState hook. We also define openModal and closeModal functions to handle the opening and closing of the modal.

Inside the return statement, we render a button that calls openModal when clicked. We also pass the isOpen prop to the Modal component, along with the onClose prop that triggers the closeModal function. Inside the Modal component, we provide the content to be displayed within the modal.

Styling the Modal

To make our modal visually appealing, we need to add some CSS styles. Here is a basic way to style your modal. Create a new file called Modal.css in the src directory and add the following styles:

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.modal-close {
  margin-top: 10px;
}

In the above styles, we position the modal as a fixed element that covers the entire screen. The background color is set to a semi-transparent black to create an overlay effect. The modal content has a white background with some padding and border-radius to give it a card-like appearance. Finally, we add some margin to the close button. There are many more ways to style React components.

Importing CSS in the App Component

To apply the styles to our modal, we need to import the Modal.css file into our App component. Open the src/App.js file and add the following line at the top:

import './Modal.css';

With this import statement, the CSS styles will be applied to the modal component.

Running the Application

Now that we have completed the implementation, let’s run our React application. In the terminal, make sure you are in the project directory (react-modal-example) and run the following command:

npm start

This will start the development server, and you should see the application running in your browser at http://localhost:3000. Click the “Open Modal” button, and the modal should appear with the provided content. Clicking the “Close” button or outside the modal will close it.

Share with a friend:

Rajae Robinson

Rajae Robinson is a young Software Developer with over 3 years of work experience building websites and mobile apps. He has extensive experience with React.js and Next.js.

Recent Posts