With Tailwind v4.0 removing tailwind.config.js, the approach to dark mode has also changed! No worries, though—here’s how you can set it up in your React app.
I will show you the easiest way to implement dark mode with React and tailwind v4.0
▶️ Install Tailwind CSS
Follow the official Tailwind Docs to install Tailwind in your React project.
▶️ Configure Global CSS
Since tailwind.config.js is no longer available, add the following to your index.css:
@import "tailwindcss";
@custom-variant dark (&:is(.dark *));
▶️ Create a Dark Mode Toggle Component
import React from 'react'
import { useEffect } from 'react';
import { useState } from 'react'
function ToggleTheme() {
const [theme, setTheme] = useState(localStorage.getItem('theme') || 'light');
useEffect(()=>{
localStorage.setItem('theme',theme);
document.documentElement.classList.toggle('dark', theme === 'dark');
},[theme])
const toggleTheme = ()=>{
setTheme(theme === 'light' ? 'dark':'light');
}
return (
<button onClick={toggleTheme} className='text-black dark:text-white'> {theme === 'light' ? 'Dark Mode' : 'Light Mode'}</button>
)
}
export default ToggleTheme;
Just import this ToggleTheme component anywhere in your project, and you're good to go! Your React app will now have a functional dark mode switch.
Like & share if this helped!💡
Top comments (0)