Dynamic Theming

Learn how to implement dynamic theme switching based on user preferences.

System Preference Detection

Automatically detect and apply the user's system theme preference:

import { initTheme } from 'ospinajuanp-reset-css/api';

// This will automatically detect system preference
initTheme();

// Or explicitly set 'system' to let it detect automatically
initTheme('dark'); // This applies dark theme directly

User Preference Storage

Persist user theme choice in localStorage:

import { setTheme, getTheme } from 'ospinajuanp-reset-css/api';

// On app init
const savedTheme = localStorage.getItem('theme') || 'system';
setTheme(savedTheme);

// On theme change
function handleThemeChange(newTheme) {
  setTheme(newTheme);
  localStorage.setItem('theme', newTheme);
}

React Implementation

Combine with React hooks for a complete solution:

import { useEffect, useState } from 'react';
import { useTheme } from 'ospinajuanp-reset-css/react';

function ThemeManager() {
  const { theme, setTheme } = useTheme();

  useEffect(() => {
    // Restore saved preference on mount
    const saved = localStorage.getItem('theme');
    if (saved) setTheme(saved);
  }, []);

  const handleChange = (newTheme) => {
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme);
  };

  return (
    <select value={theme} onChange={(e) => handleChange(e.target.value)}>
      <option value="simple">Simple</option>
      <option value="dark">Dark</option>
      <option value="pastel">Pastel</option>
    </select>
  );
}

CSS Variables Override

The themes use CSS custom properties. Override them globally:

/* Custom overrides */
:root {
  --color-primary: #your-brand-color;
  --color-background: #your-bg-color;
  --color-text: #your-text-color;
}

Best Practices

  • Always provide a theme toggle in your UI
  • Remember user choice in localStorage or cookies
  • Respect system preference as default
  • Add transition effects for smooth theme switching