Generate theme switching logic for your application
Sample text to preview the theme colors
Sample text to preview the theme colors
/* Theme Variables */
/* LIGHT Theme */
:root[data-theme="light"],
.theme-light {
--bg-primary: #ffffff;
--text-primary: #111827;
--border-color: #e5e7eb;
}
/* DARK Theme */
:root[data-theme="dark"],
.theme-dark {
--bg-primary: #111827;
--text-primary: #f9fafb;
--border-color: #374151;
}
/* System Dark Mode Preference */
@media (prefers-color-scheme: dark) {
:root:not([data-theme]) {
--bg-primary: #111827;
--text-primary: #f9fafb;
--border-color: #374151;
}
}
import { createContext, useContext, useEffect, useState, ReactNode } from 'react';
type Theme = 'light' | 'dark';
interface ThemeContextType {
theme: Theme;
setTheme: (theme: Theme) => void;
themes: Theme[];
}
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setThemeState] = useState<Theme>('light');
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
// Get theme from localStorage or system preference
const stored = localStorage.getItem('theme') as Theme;
if (stored) {
setThemeState(stored);
} else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
setThemeState('dark');
}
}, []);
useEffect(() => {
if (!mounted) return;
const root = document.documentElement;
// Remove all theme classes
root.classList.remove('theme-light');
root.classList.remove('theme-dark');
// Add current theme class
root.classList.add(`theme-${theme}`);
// Set data attribute
root.setAttribute('data-theme', theme);
// Store in localStorage
localStorage.setItem('theme', theme);
}, [theme, mounted]);
const setTheme = (newTheme: Theme) => {
setThemeState(newTheme);
};
if (!mounted) {
return null;
}
return (
<ThemeContext.Provider value={{ theme, setTheme, themes: ['light', 'dark'] }}>
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
const context = useContext(ThemeContext);
if (context === undefined) {
throw new Error('useTheme must be used within a ThemeProvider');
}
return context;
}
// Theme Switcher Component
export function ThemeSwitcher() {
const { theme, setTheme, themes } = useTheme();
return (
<div className="theme-switcher">
<label htmlFor="theme-select">Theme:</label>
<select
id="theme-select"
value={theme}
onChange={(e) => setTheme(e.target.value as Theme)}
>
{themes.map((t) => (
<option key={t} value={t}>
{t.charAt(0).toUpperCase() + t.slice(1)}
</option>
))}
</select>
</div>
);
}
// Theme Toggle Button (for light/dark)
export function ThemeToggle() {
const { theme, setTheme } = useTheme();
const toggleTheme = () => {
setTheme(theme === 'light' ? 'dark' : 'light');
};
return (
<button
onClick={toggleTheme}
className="theme-toggle"
aria-label="Toggle theme"
>
{theme === 'light' ? '🌙' : '☀️'}
</button>
);
}
Help others discover this tool!