Installation
npx nuecrea-ui add switch
Usage
import * as Field from '@/components/ui/field';
import * as Switch from '@/components/ui/switch';
const label = 'flex items-center gap-2 text-sm';
export default function SwitchStory() {
return (
<main className="grid max-w-sm gap-4">
<label className={label}>
<Switch.Root>
<Switch.Thumb />
</Switch.Root>
Airplane mode
</label>
<label className={label}>
<Switch.Root defaultChecked>
<Switch.Thumb />
</Switch.Root>
Wi-Fi
</label>
<label className={label}>
<Switch.Root disabled readOnly defaultChecked>
<Switch.Thumb />
</Switch.Root>
Managed by your admin
</label>
<Field.Root validationMode="onChange">
<Field.Label className={label}>
<Switch.Root name="backups" required>
<Switch.Thumb />
</Switch.Root>
Enable backups
</Field.Label>
<Field.Error match="valueMissing">Backups must be on.</Field.Error>
</Field.Root>
</main>
);
}
API reference
Switch.Root
The switch. Labelled by a wrapping <label> or a Field.Label. Renders <span> with role switch.
| Prop | Type | Default | Description |
|---|
checked | boolean | — | Controlled checked state. |
defaultChecked | boolean | false | Initial checked state when uncontrolled. |
name | string | — | Name of the hidden input for form submission. |
value | string | — | Value of the hidden input when checked. |
disabled | boolean | false | Ignores interaction and is removed from the tab order. |
readOnly | boolean | false | Focusable but cannot be toggled. |
required | boolean | false | Must be checked for the form/field to be valid (valueMissing). |
| Event | Payload | Description |
|---|
onCheckedChange | boolean | Fired when the user toggles the switch. Angular: the `checked` model's change event. |
| Data attribute | Present when |
|---|
data-checked | checked |
data-unchecked | not checked |
data-disabled | disabled |
data-readonly | read-only |
data-required | required |
data-valid | in a Field: validated and valid |
data-invalid | in a Field: validated and invalid |
data-dirty | in a Field: checked state differs from initial |
data-touched | in a Field: has been blurred |
data-filled | in a Field: checked |
data-focused | in a Field: focused |
Switch.Thumb
The sliding knob. Always rendered. Renders <span>.
| Data attribute | Present when |
|---|
data-checked | checked |
data-unchecked | not checked |
data-disabled | disabled |
data-readonly | read-only |
data-required | required |
data-valid | in a Field: validated and valid |
data-invalid | in a Field: validated and invalid |
data-dirty | in a Field: checked state differs from initial |
data-touched | in a Field: has been blurred |
data-filled | in a Field: checked |
data-focused | in a Field: focused |