Theme Switcher

A button component that toggles between light and dark themes with localStorage persistence.

Try it! Click the sun/moon icon in the site header to toggle between light and dark modes.
Basic
Click to toggle theme

Button Variants

The theme switcher supports all button variants.

Variants

outline

ghost

secondary

primary

Icon Sizes

Control the icon size with the icon_class prop.

Icon Sizes

size-3

size-4 (default)

size-5

size-6

With Tooltip

Add a tooltip with the tooltip prop. Control position with tooltip_side .

With Tooltip

Setup

Add this script to your root layout's <head> to prevent flash of unstyled content and enable theme persistence.

<script>
  (function() {
    const theme = localStorage.getItem('sutra-ui:theme') ||
      (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
    if (theme === 'dark') document.documentElement.classList.add('dark');
    
    window.addEventListener('sutra-ui:set-theme', (e) => {
      const newTheme = e.detail?.theme;
      if (newTheme === 'dark') {
        document.documentElement.classList.add('dark');
      } else {
        document.documentElement.classList.remove('dark');
      }
      localStorage.setItem('sutra-ui:theme', newTheme);
    });
  })();
</script>

How It Works

  • Theme preference is stored in localStorage under sutra-ui:theme
  • Falls back to system preference ( prefers-color-scheme ) if no stored preference
  • Toggles the .dark class on the document root
  • Changes sync across browser tabs automatically