17 — Form
Toggle
A button that stays in when pressed, and out when pressed again.
Installation
pnpm dlx @human-kit/design add togglenpx @human-kit/design add toggleyarn dlx @human-kit/design add togglebunx @human-kit/design add toggleThe command copies the files to src/lib/components/ui/toggle. It also
installs the packages that the files import.
Usage
<script lang="ts">
import * as Toggle from '$lib/components/ui/toggle';
import Bold from '@lucide/svelte/icons/bold';
let bold = $state(false);
</script>
<Toggle.Root size="icon" aria-label="Bold" bind:selected={bold}><Bold /></Toggle.Root> Guidelines
- Use a toggle for a state that stays on until pressed again: bold in an editor, a filter left on. For an action that runs once, use a
Button.Root. - For a setting that takes effect at once, as in a settings page, a
Switch.Rootreads better. A toggle belongs in a toolbar. - Use
ghostin a toolbar of icons,outlinebeside the buttons of a form, where it needs the same box. - Keep the label the same in and out: "Bold", not "Make bold" then "Remove bold". The pressed look says the state.
- Several toggles that work as one control, such as text styles, go in a
ToggleGroup.Root.
Accessibility
- It renders a native
<button type="button">witharia-pressed, so a screen reader says whether it is on. EnterandSpacepress it. The focus ring shows for the keyboard only.- A toggle with an icon and no text needs an
aria-label. Keep it the same in both states:aria-pressedalready says which. disabledturns it off and takes it out of the tab order.
API reference
| Prop | Type | Default |
|---|---|---|
variant | 'ghost' | 'outline' No box until the pointer is on it, or a box with an edge as a button has. | 'ghost' |
size | 'sm' | 'default' | 'lg' | 'icon-sm' | 'icon' | 'icon-lg' The height. The | 'default' |
selected | boolean Whether it is pressed in. Bindable. | — |
defaultSelected | boolean Whether it starts pressed in, when you give no | false |
onChange | (selected: boolean) => void Called when a press turns it on or off. | — |
disabled | boolean Turns the toggle off and takes it out of the tab order. | false |
element | HTMLButtonElement | null The rendered element. Bindable. | — |
Plus every attribute of a native <button>, but type and aria-pressed, which the toggle sets.