Switch
An on and off setting that takes effect at once, with its label.
Installation
pnpm dlx @human-kit/design add switchnpx @human-kit/design add switchyarn dlx @human-kit/design add switchbunx @human-kit/design add switchThe command copies the files to src/lib/components/ui/switch. It also
installs the packages that the files import.
Usage
<script lang="ts">
import * as Switch from '$lib/components/ui/switch';
let reminders = $state(true);
</script>
<Switch.Root label="Remind the patient by email" bind:checked={reminders} /> Examples
Disabled
A disabled switch fades with its label and leaves the tab order. Say in the description why it cannot change, as when the company sets it.
Set by the company.
Guidelines
- Use a switch for a setting that takes effect at once, as soon as it flips. For a choice that waits for a Save button, use a checkbox.
- Name the setting in
label, not the action: "Email reminders", not "Turn on email reminders". - Add a
descriptionwhen the effect is not plain from the name, as who sees the change. - Use
smin a dense panel of settings,defaultin a form, andlgin a toolbar beside default buttons. - Use
readonlyto show a setting the user may see but not change;disabledwhen it does not apply right now.
Accessibility
- It is a
role="switch"witharia-checked.Spaceflips it. labelrenders a<label>tied to the switch, so a click on the words flips it too. Without one, name it witharia-label.descriptiondescribes the switch througharia-describedby.disabledtakes it out of the tab order.readonlykeeps it there but stops the change.invalidputsaria-invalidon it, and the rail gets a red ring.
API reference
| Prop | Type | Default |
|---|---|---|
checked | boolean On or off. Bindable. | — |
defaultChecked | boolean The state at the start, when you give no | — |
onCheckedChange | (checked: boolean) => void Called when the user flips it. | — |
size | 'sm' | 'default' | 'lg' The height of the rail: 16, 20 or 24px. | 'default' |
label | string The words beside the switch. Without them, give | — |
description | string A line under the label. | — |
disabled | boolean Turns it off and takes it out of the tab order. | false |
readonly | boolean Keeps it focusable, but the state does not change. | — |
required | boolean The form needs it on. | — |
invalid | boolean The value is wrong: the rail gets a red ring. | false |
name | string The name the form submits while it is on. | — |
value | string The value the form submits while it is on. | — |
id | string The id of its hidden input, for a | — |
element | HTMLSpanElement | null The rendered element. Bindable. | — |
Plus every attribute of a <span>, which goes on the switch itself. A class goes on the row of switch and label when there is a label.