Switch
An on/off form control.
Anatomy
<script>
import { Switch } from '@shardsui/svelte/switch'
</script>
<Switch.Root>
<Switch.Thumb />
</Switch.Root>Usage guidelines
- Form controls must have an accessible name: provide a wrapping
<label>(recommended), anaria-label, or use the Field component. See Labeling a switch.
Examples
Labeling a switch
The simplest way to name a switch is to wrap it in a <label>:
<label>
<Switch.Root>
<Switch.Thumb />
</Switch.Root>
Autoplay
</label>Switch.Root renders a <span> by default so the wrapping <label> toggles the hidden <input type="checkbox"> natively.
Rendering as a native button
When you point a separate label at the switch with for/id instead of wrapping it, render it as a native button with as="button":
<div>
<label for="wifi-switch">Wi-Fi</label>
<Switch.Root id="wifi-switch" as="button">
<Switch.Thumb />
</Switch.Root>
</div>Form integration
Field wires the label and form association:
<Form>
<Field.Root name="autoplay">
<Field.Label>
<Switch.Root>
<Switch.Thumb />
</Switch.Root>
Autoplay
</Field.Label>
</Field.Root>
</Form>When wrapped in Field.Root, the switch takes the field's name and disabled, and toggling it runs the field's validation.
API reference
Root
Represents the switch itself.
Renders a <span> element and a hidden <input> beside.
Thumb
The movable part that indicates whether the switch is on or off.
Renders a <span> element.