Building Modals in ReactJS A Step-by-Step Guide
Tags: modals, react, reactmodal, beginners
Published: 2023-07-03 02:46:44

## Introduction:
Modals play a crucial role in enhancing user experience by displaying important information or interactive components in a visually appealing manner. In this tutorial, we will walk through the process of creating modals in ReactJS. 

## Prerequisites:
Before starting this tutorial, you should have a basic understanding of ReactJS and JavaScript. Familiarity with React functional components and React hooks, such as useState and useEffect, will be beneficial.

This is how the final code output would look like:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dx35rvmkytotbekf4xu4.png)

Now, let's dive into the tutorial on how to achieve this:

### Step 1: Setting Up the Project
To begin, create a new React project by running the following command in your terminal:

```
npx create-react-app modal-demo
```

Navigate to the project directory and start the development server:

``` bash
cd modal-demo
npm start
```

### Step 2: Creating the Modal Component
In this step, we will create a new file called **Modal.js** inside the src directory. Open the file and add the following code:

```js
import React, { useEffect } from 'react';
import './Modal.css';

const Modal = ({ isOpen, onClose, children }) => {
  useEffect(() => {
    const handleEscape = (event) => {
      if (event.key === 'Escape') {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener('keydown', handleEscape);
    }

    return () => {
      document.removeEventListener('keydown', handleEscape);
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

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

export default Modal;
```

- 
The Modal component is a functional component that takes three props: **isOpen** (a boolean indicating whether the modal is open or closed), **onClose** (a function to be called when the modal is closed), and **children** (the content to be displayed inside the modal).




- 
The **useEffect** hook is used to add and remove an event listener for the *keydown* event. When the modal is open (**isOpen** is true), the event listener is added to detect the 'Escape' key press. If the 'Escape' key is pressed, the **onClose** function is called to close the modal.

- 
The cleanup function returned by the **useEffect** hook is responsible for removing the event listener when the modal is closed or when the component unmounts.
If the modal is not open (*isOpen* is false), the component returns null, rendering nothing.

In React, components can be mounted and unmounted based on their visibility in the DOM. When a component is mounted, it means it has been inserted into the DOM and is actively rendered. Conversely, when a component is unmounted, it means it has been removed from the DOM and is no longer rendered.

In the case of the Modal component, the unmounting happens when the component is closed or when the App component that renders it is unmounted. When the App component unmounts, all its child components, including the Modal component, will also unmount.


## Step 3: Styling the Modal
To make the modal visually appealing, let's add some CSS styles. Create a new file called Modal.css inside the src directory and add the following CSS code:

### Step 3: Styling the Modal

To make the modal visually appealing, let's add some CSS styles. Create a new file called Modal.css inside the src directory and add the following CSS code:


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

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

.close {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
  font-size: 24px;
}
```

- The .modal class is used to style the container of the modal. It 
  uses flex to center the content both horizontally and vertically within the viewport.


- The .modal-content class is applied to the inner content of the modal. It sets the background color, padding, and border-radius to give it a card-like appearance.


- The .close class is used to style the close button of the modal. It positions the button in the top-right corner and sets its font size.


### Step 4: Implementing the Modal in Your App

Now, let's integrate the Modal component into your application. Open the App.js file and replace its content with the following code:

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

const App = () => {
  const [modalOpen, setModalOpen] = useState(false);

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

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

  return (
    <div>
      <h1>Modal Demo</h1>
      <button onClick={openModal}>Open Modal</button>
      <Modal isOpen={modalOpen} onClose={closeModal}>
        <h2>Modal Content</h2>
        <p>This is the content of the modal.</p>
      </Modal>
    </div>
  );
};

export default App;
```




### Step 5: Run the Application

### Enhancing the Modal
Congratulations! You have successfully built a basic modal in ReactJS. Now, let's explore some use cases and additional enhancements to make your modals more attractive and functional.

### Use Cases

**User Login/Registration:** 
Display a modal form for users to log in or register.

**Confirmations:** 
Ask user-s to confirm their actions with a modal dialog, such as deleting a post or unsubscribing from a newsletter.

 **Product Information:**
 Show detailed information about a product in a modal when a user clicks on it.

**Image Galleries:**
 Create a modal gallery for displaying images in a larger view.

References for using Ready to use Dialog boxes
https://headlessui.com/react/dialog 
https://ant.design/components/modal
https://mui.com/material-ui/react-dialog/
https://chakra-ui.com/docs/components/modal


### Conclusion:

In this tutorial, you learned how to create modals in ReactJS. By following the step-by-step instructions and reviewing the code examples, you now have the knowledge to implement modals in your React applications.