Switch
The Switch component is used as an alternative between checked and not checked states.
Installation
The above command is for individual installation only. You may skip this step if @nextui-org/react
is already installed globally.
Import
Usage
With Label
Disabled
Sizes
Colors
With Thumb Icon
With Icons
You can also add icons to start and end of the switch by using startContent
and endContent
props.
Controlled
Note: NextUI
Switch
also supports native events likeonChange
, useful for form libraries such as Formik and React Hook Form.
Slots
- base: Base slot for the switch. It is the main wrapper.
- wrapper: The wrapper of the start icon, end icon and thumb.
- hiddenInput: The hidden input element that is used to handle the switch state.
- thumb: The thumb element of the switch. It is the circle element.
- label: The label slot of the switch.
- startContent: The icon slot at the start of the switch.
- endContent: The icon slot at the end of the switch.
- thumbIcon: The icon slot inside the thumb.
Custom Styles
You can customize the Switch
component by passing custom Tailwind CSS classes to the component slots.
Custom Implementation
In case you need to customize the switch even further, you can use the useSwitch
hook to create your own implementation.
Data Attributes
Switch
has the following attributes on the base
element:
- data-selected:
When the switch is checked. Based on
isSelected
prop. - data-pressed: When the switch is pressed. Based on usePress
- data-readonly:
When the switch is readonly. Based on
isReadOnly
prop. - data-hover: When the switch is being hovered. Based on useHover
- data-focus: When the switch is being focused. Based on useFocusRing.
- data-focus-visible: When the switch is being focused with the keyboard. Based on useFocusRing.
- data-disabled:
When the switch is disabled. Based on
isDisabled
prop.
Accessibility
- Built with a native HTML
<input>
element. - Full support for browser features like form autofill.
- Keyboard focus management and cross browser normalization.
- Keyboard event support for Tab and Space keys.
- Labeling support for assistive technology.
- Exposed as a switch to assistive technology via ARIA
API
Switch Props
Prop | Type | Default |
children |
| |
value |
| |
name |
| |
size |
| "md" |
color |
| "primary" |
thumbIcon |
| |
startContent |
| |
endContent |
| |
isSelected |
| |
defaultSelected |
| |
isReadOnly |
| |
isDisabled |
| false |
disableAnimation |
| false |
classNames |
|
Switch Events
Prop | Type | Default |
onChange |
| |
onValueChange |
|