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
Create Feeds UI using React and Tailwind CSS
In the world of social networking, feeds are the primary way users interact with content. Whether it is on LinkedIn, Facebook, or Twitter the feed showcases posts updates, and activities from people or organizations. This article will help you build a LinkedIn-style feed UI using React and Tailwind
4 min read
Create Dropdowns UI using React and Tailwind CSS
Dropdown UI components are often used in web applications for forms, navigation, or user preferences, allow users to select from a list of options by clicking a button, which will display a drop-down menu, in this article we will create a dropdown element using React for functionality and Tailwind C
3 min read
Create Navbars UI using React and Tailwind CSS
A UI plays an important role because a clean, well-designed interface creates a positive first impression and if the UI is good then users can stay on our website some more time and if the UI is bad then they can not stay on our site for more time. we will see how to Create Navbars UI using React an
5 min read
Create Radio Groups UI using React and Tailwind CSS
React is a popular JavaScript library for building user interfaces combined with Tailwind CSS a utility-first CSS framework that offers a powerful approach to developing stylish and responsive components. This article shows how to build various radio group UIs using React and Tailwind CSS. It includ
5 min read
Create Pagination UI Using React And Tailwind CSS
When working with huge data sets in online applications, pagination is an essential feature. It makes a lengthy list of items easier to browse through by dividing them into digestible parts. This article will tell you how to use Tailwind CSS for styling and React for front-end functionality to creat
3 min read
Create FAQs using React and Tailwind CSS
A Frequently Asked Questions section is a common feature found on websites and applications that helps users find answers to common queries in an organized manner. A well-designed FAQ can improve user experience reduce support requests and provide users with quick and easy access to helpful informat
5 min read
Create Flyout Menus using React and Tailwind CSS
Flyout menus are a type of navigational menu that can be displayed when the user hovers over or clicks on an item allowing for a clean and organized display of additional options without crowding the main interface. In this article, we will create a responsive flyout menu using React and Tailwind CS
4 min read
Create Order History Page using React and Tailwind CSS
We will create an order history page using React and Tailwind CSS. This page will display a list of previous orders in a clean and responsive layout. We'll incorporate basic functionalities like listing the order details (order ID, date, total amount, and status) and styling them using Tailwind CSS.
3 min read
Create Command Palettes UI using React and Tailwind CSS
This article shows you how to create a Command Palette UI using React and Tailwind CSS. A command palette lets users easily search for and run commands within an app, making navigation faster and more efficient. Weâll walk you through building a simple and intuitive interface where users can type, s
4 min read
Create Product Features using React and Tailwind CSS
The goal is to build a React component that displays a list of credit card features alongside an image of the card itself. The features will include benefits such as rewards cashback and fraud protection each accompanied by an icon. Tailwind CSS will be used for styling to ensure responsive and mode
4 min read