The Switch component is used as an alternative for the Checkbox component. You can switch between enabled or disabled states. Switch must always be accompanied by a label, and follows the same keyboard workflow as a Checkbox.
Features
There is no native HTML element with switch styling. <input type="checkbox"> is the closest semantically, but isn't styled or exposed to assistive technology as a switch.
- Built with a native HTML
<input>element, which is visually hidden to allow custom styling - Full support for browser features like form autofill
- Keyboard focus management and cross browser normalization
- Labeling support for screen readers
- Exposed as a switch to assistive technology via ARIA
Usage
import { Switch } from '@console/nimbus-ui/core';Examples
Controlled
Uncontrolled
Switches can be used in an uncontrolled way by utilising the <form/> html component.
The following form will automatically submit using the url params. If you press "submit"
you can see the params in the URL change based on the off/on state of the input.
Sizes
Pass the size prop to change the size of the Switch.
Default Selected
Pass the defaultSelected prop to toggle on default selected (uncontrolled).
If you're using a controlled version of the Switch, use the isSelected prop.
Disabled
States like isDisabled & isReadOnly have an impact on the usability of a Switch and on the styles.
Auto Focus
Pass the autoFocus prop to automatically toggle focus. This is commonly used within modals or popovers to not focus trap the user.
Children
Take advantage of the children prop to generate more complex layouts for forms. We use the style prop here, but a className via the classes API would be much better for this usecase. In the future we intend to make the Switch API more accessible and easier to style for this usecase.
API
| Prop | Type | Default | Description |
|---|---|---|---|
| classes | { container?: string; track?: string; label?: string; thumb?: string; } | — | Override or extend the styles applied to the component. |
| data-testid | string | — | id for E2E testing purposes |
| disabled | boolean | — | Whether the input is disabled. |
| readonly | boolean | — | Whether the input can be selected but not changed by the user. |
| selected | boolean | — | Whether the Switch should be selected (controlled). |
| size | enum | sm | Predefined size value |
React Aria
Figma