Dark/Light Mode Toggle
Add a theme toggle button to your site so users can switch between dark and light mode.
Step 1: Create the Theme Toggle Component
Create a new file at src/components/theme-toggle.tsx
and add the following code:
import { useTheme } from 'next-themes';
import { Moon, Sun } from 'lucide-react';
export function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
<button
onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
className="px-4 py-2 rounded-lg border border-white font-semibold transition-colors duration-200 bg-black text-white dark:bg-white dark:text-black"
>
{theme === 'dark' ? <Sun className="inline h-5 w-5" /> : <Moon className="inline h-5 w-5" />}
{theme === 'dark' ? ' Light Mode' : ' Dark Mode'}
</button>
);
}
tsx
Step 2: Use the Theme Toggle in Your Navbar or Layout
Import and add the ThemeToggle
to your Navbar
or layout.tsx
:
import { ThemeToggle } from '@/components/theme-toggle';
export function Navbar() {
return (
<nav>
{/* ...other nav content... */}
<ThemeToggle />
</nav>
);
}
tsx
Live Example
(Click to toggle theme)