Switch
A control that allows the user to toggle between checked and not checked.
Features
- Full keyboard navigation
- Can be controlled or uncontrolled
Anatomy
- Root: The root container for the switch
- Input: The native HTML input that is visually hidden
Usage
To create a switch, use the createSwitch
builder function. You can then reference the anatomy or
example above to create your switch.
Disabling the switch
To disable the switch, set the disabled
argument as true
.
API Reference
createSwitch
The builder function used to create the switch component.
Props
Prop | Default | Type / Description |
disabled | false | boolean Whether or not the switch is disabled. |
required | false | boolean Whether or not the switch is required. |
name | - | string The name of the hidden input element used for form submission.. |
value | - | string The value of the hidden input element used for form submission. |
defaultChecked | false | boolean The initial checked state of the switch. |
checked | - | Writable<boolean> The controlled checked state store of the switch. If provided, this will override the value passed to |
onCheckedChange | - | ChangeFn<boolean> A callback called when the value of the See Change Functions |
Elements
States
State | Description |
checked | A writable store that returns whether or not the switch is checked. |
Options
Option | Description |
disabled | Whether or not the switch is disabled. |
required | Whether or not the switch is required. |
name | The name of the hidden input element used for form submission.. |
value | The value of the hidden input element used for form submission. |
root
The switch element.
Data Attributes
Data Attribute | Value |
[data-disabled] | Present when the switch is disabled. |
[data-state] |
|
[data-melt-switch] | Present on all switch elements. |
Custom Events
Event | Value |
m-click | (e: ) => void |
m-keydown | (e: ) => void |
input
The hidden input element used for form submission.
Data Attributes
Data Attribute | Value |
[data-melt-switch-input] | Present on all input elements. |
Accessibility
Adheres to the Switch WAI-ARIA design pattern
Key | Behavior |
Space | When the switch has focus, toggles the switch. |
Enter | When the switch has focus, toggles the switch. |
On This Page