Creating a Reusable Modal Component in React With Tailwind CSS
Modals are essential UI components for showing alerts, forms, or additional content without navigating away from the current page. In this guide, we’ll build a reusable modal component in React using Tailwind CSS for styling.
Step 1: Set Up Your React Environment
Start with a fresh React project. If you don’t have Tailwind CSS installed, you can add it with:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Then configure your tailwind.config.js
and index.css
accordingly.
Step 2: Create the Modal Component
Build a modal that accepts props for visibility, close function, and content.
// Modal.js
export default function Modal({ isOpen, onClose, children }) {
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 p-6 rounded shadow-lg max-w-md w-full relative">
<button
onClick={onClose}
className="absolute top-2 right-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300">
✕
</button>
{children}
</div>
</div>
);
}
Step 3: Use the Modal in Your App
Integrate the modal in your main component with a button to open it.
// App.js
import { useState } from "react";
import Modal from "./Modal";
function App() {
const [showModal, setShowModal] = useState(false);
return (
<div className="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-900">
<button
onClick={() => setShowModal(true)}
className="px-4 py-2 bg-blue-600 text-white rounded">
Open Modal
</button>
<Modal isOpen={showModal} onClose={() => setShowModal(false)}>
<h2 className="text-xl font-bold mb-4">Hello from the Modal!</h2>
<p>This is a reusable modal component styled with Tailwind CSS.</p>
</Modal>
</div>
);
}
export default App;
Conclusion
Building reusable UI components like a modal helps keep your code clean and maintainable. With Tailwind CSS and React hooks, you can quickly create flexible, styled components that enhance your user experience.
For a much more extensive guide on getting the most out of React portals, check out my full 24-page PDF file on Gumroad. It's available for just $10:
Using React Portals Like a Pro.
If this post helped you, consider supporting me: buymeacoffee.com/hexshift
Top comments (0)