Switch
This is a boolean switch. You can control the checked state, or you can let the component control it. A hidden input gives the form support, and the thumb part has no styles.
Anatomy
The switch has two parts. Switch.Root makes the track and a hidden checkbox input for the form. Switch.Thumb makes the indicator that moves.
<script>
import { Switch } from '@human-kit/ui';
</script>
<Switch.Root aria-label="Enable notifications">
<Switch.Thumb />
</Switch.Root>States
Both parts show each visual state in data-* attributes. Thus you write all of the styles in plain CSS or in utility classes. This includes the styles for the disabled state and the readonly state.
Forms
Switch.Root keeps a hidden checkbox correct. Give the root a name and a value. If the switch is on, the form submits the pair. The value prop changes only the form submission. It does not change the visual state.
Usage guidelines
- Use
checkedanddefaultCheckedfor the state of the switch. - Use
onCheckedChangeto react when the user changes the state. - Use
valueonly for the form submission through the hidden native input. Thevalueprop does not show the visual state. - Put the switch in a native
<label>element. This is the most simple label pattern. As an alternative, point alabel[for]element at theidof the switch.
Accessibility
Switch.Roothasrole="switch"witharia-checked="true" | "false".- Push the
Spacekey to change the switch. - The
readonlyprop keeps the switch focusable, but it stops the state changes.
API reference
Root
The switch control. It makes a span with role="switch", and it keeps a hidden checkbox input correct for the form.
* required. Native HTML attributes of the underlying element are also accepted.
Thumb
The indicator that moves. It shows the state of the root in data attributes, for the styles.
* required. Native HTML attributes of the underlying element are also accepted.