Theme Toggle

Switch between light and dark themes with localStorage persistence.

Live Demo

Source

HTML + JavaScript
<div data-component="theme-toggle" data-storage-key="my-theme" data-auto-save>
    <button data-action="toggleTheme" data-bind="buttonLabel"></button>
    <span data-bind="currentLabel"></span>
</div>

<script>
wildflower.component('theme-toggle', {
    state: {
        isDark: true
    },
    computed: {
        buttonLabel() {
            return this.isDark ? 'Switch to Light' : 'Switch to Dark';
        },
        currentLabel() {
            return 'Current: ' + (this.isDark ? 'Dark' : 'Light');
        }
    },
    toggleTheme() {
        this.isDark = !this.isDark;
        document.documentElement.className = 'theme-' + (this.isDark ? 'dark' : 'light');
    }
});
</script>

Key Points

  • data-storage-key + data-auto-save on the component element persists state to localStorage automatically
  • The toggle method just flips state and applies the CSS class. No manual localStorage calls needed
  • Computed properties derive the button label from state. No manual DOM updates
  • Define your theme CSS variables on .theme-light and .theme-dark classes