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/
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read