Theme Toggle for React
An accessible light and dark theme toggle for React and Tailwind CSS with persistent state, an explicit accessible label and smooth visual feedback.
Copy the code
'use client'
import { useEffect, useState } from 'react'
export function ThemeToggle() {
const [dark, setDark] = useState(true)
useEffect(() => {
document.documentElement.classList.toggle('dark', dark)
localStorage.setItem('theme', dark ? 'dark' : 'light')
}, [dark])
return (
<button type="button" onClick={() => setDark(value => !value)}
aria-label={dark ? 'Switch to light mode' : 'Switch to dark mode'}
className="flex h-11 w-20 items-center rounded-full bg-slate-200 p-1 transition dark:bg-slate-800">
<span className={'grid h-9 w-9 place-items-center rounded-full bg-white shadow transition-transform ' + (dark ? 'translate-x-9' : '')}>
{dark ? '☀' : '☾'}
</span>
</button>
)
}Tailwind CSS · no dependencies · MIT licensed. Paste it straight into any React, Next.js or Vite project.
About the theme toggle
This theme toggle is part of Empire UI - a free, open-source library of 34+ component types rendered across 41 visual styles, from glassmorphism to neo-brutalism. Every block is copy-paste ready in React and Tailwind CSS with no runtime dependencies.
Want it in a different look? Browse all 41 styles or grab the matching glassmorphism components.