DEV Community

Cover image for Implement Dark Mode in Tailwind v4.0 + React ๐ŸŒ™
Muhammad Hassam
Muhammad Hassam

Posted on

Implement Dark Mode in Tailwind v4.0 + React ๐ŸŒ™

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 *));
Enter fullscreen mode Exit fullscreen mode

โ–ถ๏ธ 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;
Enter fullscreen mode Exit fullscreen mode

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)