Building a Dark Mode Toggle in React With Tailwind CSS
Dark mode is a popular feature that improves readability and reduces eye strain in low-light environments. With Tailwind CSS and React, implementing a toggle between light and dark themes is straightforward. In this guide, we’ll walk through the process step by step.
Step 1: Set Up Your React App
Start by creating a new React project using Vite or Create React App.
npx create-react-app dark-mode-toggle
cd dark-mode-toggle
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Then configure your tailwind.config.js
like this:
module.exports = {
content: ["./src/**/*.{js,jsx,ts,tsx}"],
darkMode: 'class',
theme: {
extend: {},
},
plugins: [],
}
Step 2: Create the Toggle Functionality
In your main component (e.g., App.js
), use state to toggle a dark
class on the root element:
import { useEffect, useState } from "react";
function App() {
const [darkMode, setDarkMode] = useState(false);
useEffect(() => {
if (darkMode) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
}, [darkMode]);
return (
<div className="min-h-screen flex items-center justify-center bg-white dark:bg-gray-900 text-black dark:text-white">
<button
onClick={() => setDarkMode(!darkMode)}
className="px-4 py-2 rounded bg-gray-200 dark:bg-gray-800">
Toggle Dark Mode
</button>
</div>
);
}
export default App;
Step 3: Styling With Tailwind’s Dark Classes
Use Tailwind’s dark:
prefix to style elements differently in dark mode. In the example above, we changed background and text colors based on the mode.
Conclusion
With React and Tailwind CSS, adding a dark mode toggle is quick and highly customizable. This is a great way to enhance user experience and make your projects feel more polished.
If this post helped you, consider supporting me: buymeacoffee.com/hexshift