Skip to content
TallCraftUI

Theme toggle

A button that switches between light and dark mode. It stores the choice in localStorage, falls back to the operating system setting and keeps every toggle on the page in sync.

Basic usage

Click it: the whole site switches, including the toggle in the header.

Blade
<x-theme-toggle />

Customize the toggle

Style the button with class and each icon with class:icon-light and class:icon-dark.

Blade
<x-theme-toggle class="rounded-md border border-gray-200 dark:border-gray-700" />
 
<x-theme-toggle
class="size-12 bg-gray-100 dark:bg-gray-800"
class:icon-light="size-6 text-amber-500"
class:icon-dark="size-6 text-indigo-400"
/>

React to theme changes

Each toggle dispatches a tallcraftui-theme-changed window event with detail.dark. Listen for it to update charts, maps or anything else that doesn't use Tailwind classes.

Blade
<div x-data="{ dark: document.documentElement.classList.contains('dark') }"
@tallcraftui-theme-changed.window="dark = $event.detail.dark">
<span x-text="dark ? 'Dark mode' : 'Light mode'"></span>
</div>

Avoid a flash of the wrong theme

The toggle applies the saved theme as soon as it renders. To apply it before the first paint, add this script to your layout's <head>:

HTML
<script>
if (localStorage.getItem('dark-mode') === 'true' ||
(!('dark-mode' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.add('dark');
}
</script>

API reference

Props are read from the component classes in TallCraftUI 3.0.0-beta.1. Write them in kebab-case and pass booleans as bare attributes, for example <x-button outline />. Other attributes, such as class or wire:model, are passed to the component's element.

<x-theme-toggle>

View source

This component has no props. Use its slot and attributes.