Buttons
Theme toggle
Switches between light and dark, remembers the choice, and spreads the new theme in a circle from the button. Until someone chooses, the page follows their system setting.
Installation
npx sinaui add theme-toggleCopy src/lib/ui/ThemeToggle.svelte, with theme.ts, Button.svelte, Icon.svelte, announce.ts and tokens.css. It needs @hugeicons/core-free-icons.
Avoid a flash of the wrong theme
The saved choice has to be applied before the page first paints. Put this in the <head> of src/app.html, above %sveltekit.head%:
<script>
try {
const t = localStorage.getItem('theme');
if (t === 'light' || t === 'dark') document.documentElement.dataset.theme = t;
} catch {}
</script>Examples
Basic
<script lang="ts">
import ThemeToggle from '#lib/ui/ThemeToggle.svelte';
</script>
<ThemeToggle />Props
| Prop | Type | Default |
|---|---|---|
label | string: the accessible name | “Dark theme” |
size | 'sm' | 'md' | 'lg' | 'md' |
To switch the theme from somewhere else, such as a menu, call setTheme(dark) from theme.ts. Every toggle on the page follows.
Keyboard
| Key | Does |
|---|---|
| Enter Space | Switches the theme |
Accessibility
- A toggle button: screen readers hear its name, “Dark theme”, and whether it is pressed (dark on).
- With reduced motion, the theme changes at once, without the circle.