Skip to the content
human-kit design
15 — Form

Switch

An on and off setting that takes effect at once, with its label.

Installation

pnpm dlx @human-kit/design add switch
npx @human-kit/design add switch
yarn dlx @human-kit/design add switch
bunx @human-kit/design add switch

The 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 description when the effect is not plain from the name, as who sees the change.
  • Use sm in a dense panel of settings, default in a form, and lg in a toolbar beside default buttons.
  • Use readonly to show a setting the user may see but not change; disabled when it does not apply right now.

Accessibility

  • It is a role="switch" with aria-checked. Space flips it.
  • label renders a <label> tied to the switch, so a click on the words flips it too. Without one, name it with aria-label.
  • description describes the switch through aria-describedby.
  • disabled takes it out of the tab order. readonly keeps it there but stops the change.
  • invalid puts aria-invalid on it, and the rail gets a red ring.

API reference

PropTypeDefault
checkedboolean

On or off. Bindable.

—
defaultCheckedboolean

The state at the start, when you give no checked.

—
onCheckedChange(checked: boolean) => void

Called when the user flips it.

—
size'sm' | 'default' | 'lg'

The height of the rail: 16, 20 or 24px.

'default'
labelstring

The words beside the switch. Without them, give aria-label.

—
descriptionstring

A line under the label.

—
disabledboolean

Turns it off and takes it out of the tab order.

false
readonlyboolean

Keeps it focusable, but the state does not change.

—
requiredboolean

The form needs it on.

—
invalidboolean

The value is wrong: the rail gets a red ring.

false
namestring

The name the form submits while it is on.

—
valuestring

The value the form submits while it is on.

—
idstring

The id of its hidden input, for a <label for> of your own.

—
elementHTMLSpanElement | 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.