Components / Choice

Switch

An on/off toggle (role=switch). Extra attributes go to the native input, which overlays the visible track so test tools can check() it directly.

@ruckc/truss-ui Choice

Import

import { Switch } from '@ruckc/truss-ui';

Playground

Recipe: reacting to a toggle

onchange receives the new state (boolean) when the user toggles the switch, by click or keyboard. It does not fire when checked is changed from code.

Last change: none

<Switch bind:checked={on} onchange={(checked) => save(checked)}>Notifications</Switch>

Recipe: function bindings for immutable state

Bind with a getter and a setter when state is updated immutably; the setter is the place to copy or validate.

Value: true

<script lang="ts">
  let prefs = $state({ notify: true });
  const setNotify = (checked: boolean) => (prefs = { ...prefs, notify: checked });
</script>

<!-- Svelte function bindings: a getter and a setter -->
<Switch bind:checked={() => prefs.notify, setNotify}>Notifications</Switch>

API

PropTypeDefaultDescription
checked bindable booleanfalseWhether it is checked. Bind it with `bind:checked`.
disabled booleanfalseDisables the control: it cannot be focused, changed or activated.
onchange event(checked: boolean) => void—Called with the new state after the user toggles the switch. Not called for programmatic changes to `checked`.
children snippet Snippet—Content, as a Svelte snippet.
aria-label string—Accessible name.
/docs/switch Truss UI · MIT