consolelog.tools logo

Theme Switcher Code

Generate theme switching logic for your application

Theme Configuration

Theme Preview

light Theme

Sample text to preview the theme colors

dark Theme

Sample text to preview the theme colors

Framework

Theme CSS

/* 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;
  }
}

Theme Switcher (React)

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>
  );
}

Implementation Steps

  1. Add the theme CSS to your global styles
  2. Wrap your app with ThemeProvider
  3. Use the useTheme hook in your components
  4. Themes will persist in localStorage automatically
  5. System dark mode preference is detected automatically

Was this tool helpful?

Share Your Experience

Help others discover this tool!

Frequently Asked Questions - Theme Switcher Code