Skip to the content
human-kit design
17 — Form

Toggle

A button that stays in when pressed, and out when pressed again.

Installation

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

The 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.Root reads better. A toggle belongs in a toolbar.
  • Use ghost in a toolbar of icons, outline beside 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"> with aria-pressed, so a screen reader says whether it is on.
  • Enter and Space press 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-pressed already says which.
  • disabled turns it off and takes it out of the tab order.

API reference

PropTypeDefault
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 icon sizes make a square for an icon alone.

'default'
selectedboolean

Whether it is pressed in. Bindable.

—
defaultSelectedboolean

Whether it starts pressed in, when you give no selected.

false
onChange(selected: boolean) => void

Called when a press turns it on or off.

—
disabledboolean

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

false
elementHTMLButtonElement | null

The rendered element. Bindable.

—

Plus every attribute of a native <button>, but type and aria-pressed, which the toggle sets.