Create a Modal Popup Component in React
Creating a modal popup component in React is a great way to add a user-friendly, interactive element to your website or application. A modal popup is a dialog box that appears on top of the current screen, allowing users to interact with the content within it.
Create a Modal Popup Component in React
To create a Modal Popup component in React:
- Create a new Component eg. ModalPopup and add methods to open and close the popup.
- Style the component using CSS and add it to the component.
- Call the ModalPopup component where you want to use it.
They are commonly used for forms, alerts, and other types of interactions. In this tutorial, we will go over the steps of creating a modal popup component in React, including setting up the basic structure, adding props and state, and styling the component with CSS.
By the end of this tutorial, you will have a fully functional modal popup component that you can use in your own projects.
Here is an example of a basic modal popup component in React:
Modal.js
import React, { useState } from 'react';
import './modal.css';
function ModalPopup({ children, title }) {
const [isOpen, setIsOpen] = useState(false);
const openModal = () => {
setIsOpen(true);
}
const closeModal = () => {
setIsOpen(false);
}
return (
<>
<button onClick={openModal}>Open Modal</button>
{isOpen && (
<>
<div className="modal-overlay"></div>
<div className="modal">
<div className="modal-title">{title}</div>
<div>
{children}
</div>
<button className="modal-close-button" onClick={closeModal}>X</button>
</div>
</>
)}
</>
);
}
export default ModalPopup;
Modal.css
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
padding: 20px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.3);
z-index: 10;
}
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 9;
}
.modal-close-button {
position: absolute;
top: 10px;
right: 10px;
font-size: 20px;
font-weight: bold;
color: gray;
cursor: pointer;
}
.modal-title {
font-size: 24px;
font-weight: bold;
margin-bottom: 20px;
}
This component uses React's useState hook to maintain the state of the modal (open or closed). The openModal() function updates the state to open the modal, and the closeModal function updates the state to close the modal.
Here is an example of how you can call the ModalPopup component in another component:
App.js
import React from 'react';
import ModalPopup from './Modal';
function App() {
return (
<div>
<ModalPopup title="My Modal">
<p>This is the content of the modal.</p>
</ModalPopup>
</div>
);
}
export default App;
In this example, the ModalPopup component is imported and used in the App component. The component takes two props, one is the "title" and the other is the content inside the modal which is passed as children.