Create Modal Dialogs UI using React and Tailwind CSS
Last Updated :
26 Sep, 2024
Modal dialogs are an essential part of modern web applications. They offer a user-friendly way to present information or collect input without navigating away from the current page. Modals typically appear as overlays which help focus the user's attention on specific tasks like forms or alerts and confirmations.
In this article, we will create a reusable modal dialog component in React styled with Tailwind CSS for a sleek and responsive design.
Prerequisites
Approach
To create modals like Alert, Confirmation, and Form Modals using React and Tailwind CSS, define a reusable Modal component that controls the modal's visibility and structure. Use Tailwind CSS for responsive and flexible styling, applying classes for layout, padding, and background opacity. Each specific modal (Alert, Confirmation, Form) can extend the base modal by passing different children components with the desired content and actions, such as buttons or forms. Use the React state to control when the modal opens and closes, ensuring a clean and reusable design for various modal types.
Steps To Create Modal Dialogs UI
Here, We will create a sample React JS project then we will install Tailwind CSS once it is completed we will start development for Modal Dialogs using React and Tailwind CSS. Below are the steps to create and configure the project:
Step 1: Set up a React Application
First, create a sample React JS application by using the mentioned command then navigate to the project folder
npx create-react-app react-app
cd react-app
Project Structure
project folderUpdated Dependencies
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"devDependencies": {
"autoprefixer": "^10.4.20",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.13"
}
Step 2: Install and Configure Tailwind CSS
Once Project is created successfully Now install and configure the Tailwind css by using below commands in your project.
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Step 3: Develop Business logic
Once Tailwind css installation and configuration is completed. Now we need develop user interface for Modal Dialogs using tailwind css and html. And it is responsive web page for this we use App.js and App.css files we provide that source code for your reference.
- App.js
- index.css
- tailwind.config.js
Here we provide some common code for all types alerts. Those are index.css and tailwind.config.js
JavaScript
/*src/tailwind.congif.js*/
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
Example 1: An alert modal is used to display a short message that requires acknowledgment. It often comes with a single OK button to dismiss the message.
JavaScript
//App.js
import React, { useState } from 'react';
const Modal = ({ isOpen, onClose, children }) => {
if (!isOpen) return null;
return (
<div className="fixed inset-0 flex
items-center justify-center
bg-black bg-opacity-50">
<div className="bg-white rounded-lg
shadow-lg p-6 max-w-md
w-full relative">
<button
className="absolute top-2 right-2
text-gray-500 hover:text-gray-700"
onClick={onClose}
>
✕ {/* Close button */}
</button>
{children}
</div>
</div>
);
};
const AlertModal = ({ isOpen, onClose }) => {
return (
<Modal isOpen={isOpen} onClose={onClose}>
<h2 className="text-lg font-bold">Alert</h2>
<p className="text-gray-700">
This is an important message.
</p>
<button
className="mt-4 px-4 py-2
bg-blue-500 text-white
rounded-lg"
onClick={onClose}
>
OK
</button>
</Modal>
);
};
const App = () => {
const [isModalOpen, setModalOpen] = useState(false);
return (
<div className="h-screen flex items-center
justify-center">
<button
className="px-4 py-2 bg-blue-500
text-white rounded-lg"
onClick={() => setModalOpen(true)}
>
Show Alert
</button>
<AlertModal isOpen={isModalOpen} onClose={() => setModalOpen(false)} />
</div>
);
};
export default App;
Output:
Example 2: A confirmation modal asks the user to confirm or cancel an action. It usually contains Yes or No buttons or Confirm and Cancel.
JavaScript
//App.js
import React, { useState } from 'react';
const Modal = ({ isOpen, onClose, children }) => {
if (!isOpen) return null;
return (
<div className="fixed inset-0 flex
items-center justify-center
bg-black bg-opacity-50">
<div className="bg-white rounded-lg
shadow-lg p-6 max-w-md
w-full relative">
<button
className="absolute top-2 right-2
text-gray-500 hover:text-gray-700"
onClick={onClose}
>
✕ {/* Close button */}
</button>
{children}
</div>
</div>
);
};
const ConfirmationModal = ({ isOpen, onClose, onConfirm }) => {
return (
<Modal isOpen={isOpen} onClose={onClose}>
<h2 className="text-lg font-bold">
Confirm Action
</h2>
<p className="text-gray-700">
Are you sure you want to proceed?
</p>
<div className="flex justify-end
space-x-4 mt-4">
<button
className="px-4 py-2 bg-gray-500
text-white rounded-lg"
onClick={onClose}
>
Cancel
</button>
<button
className="px-4 py-2 bg-red-500
text-white rounded-lg"
onClick={onConfirm}
>
Confirm
</button>
</div>
</Modal>
);
};
const App = () => {
const [isModalOpen, setModalOpen] = useState(false);
const handleConfirm = () => {
alert("Action Confirmed!");
setModalOpen(false);
};
return (
<div className="h-screen flex items-center
justify-center">
<button
className="px-4 py-2 bg-blue-500
text-white rounded-lg"
onClick={() => setModalOpen(true)}
>
Open Confirmation Modal
</button>
<ConfirmationModal
isOpen={isModalOpen}
onClose={() => setModalOpen(false)}
onConfirm={handleConfirm}
/>
</div>
);
};
export default App;
Output:
Example 3: A form modal presents a form within the modal itself, allowing users to input and submit data without leaving the current page.
JavaScript
//App.js
import React, { useState } from 'react';
const Modal = ({ isOpen, onClose, children }) => {
if (!isOpen) return null;
return (
<div className="fixed inset-0 flex items-center
justify-center bg-black bg-opacity-50">
<div className="bg-white rounded-lg
shadow-lg p-6 max-w-md
w-full relative">
<button
className="absolute top-2
right-2 text-gray-500
hover:text-gray-700"
onClick={onClose}
>
✕ {/* Close button */}
</button>
{children}
</div>
</div>
);
};
const FormModal = ({ isOpen, onClose, onSubmit }) => {
const [formData, setFormData] = useState({ name: '', email: '' });
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
onSubmit(formData);
onClose();
};
return (
<Modal isOpen={isOpen} onClose={onClose}>
<h2 className="text-lg font-bold">Submit Your Details</h2>
<form onSubmit={handleSubmit}>
<div className="mb-4">
<label className="block text-sm">Name</label>
<input
className="w-full px-3 py-2
border rounded-lg"
name="name"
value={formData.name}
onChange={handleChange}
required
/>
</div>
<div className="mb-4">
<label className="block text-sm">Email</label>
<input
className="w-full px-3
py-2 border rounded-lg"
name="email"
value={formData.email}
onChange={handleChange}
required
/>
</div>
<button
type="submit"
className="px-4 py-2 bg-green-500
text-white rounded-lg"
>
Submit
</button>
</form>
</Modal>
);
};
const App = () => {
const [isModalOpen, setModalOpen] = useState(false);
const handleSubmit = (data) => {
alert(`Submitted: ${JSON.stringify(data)}`);
};
return (
<div className="h-screen flex
items-center justify-center">
<button
className="px-4 py-2 bg-blue-500
text-white rounded-lg"
onClick={() => setModalOpen(true)}
>
Open Form Modal
</button>
<FormModal
isOpen={isModalOpen}
onClose={() => setModalOpen(false)}
onSubmit={handleSubmit}
/>
</div>
);
};
export default App;
Output:
Step 4: Run the Application
Once Development is completed Now we need run the react js application by using below command. By default the react js application run on port number 3000.
npm start
Output: Once Project is successfully running then open the below URL to test the output.
http://localhost:3000/