Switch
What is this?
Switch is a component for customizing configurations. It represents a physical switch that allows users to turn things on or off, providing control over actions and preferences. Tapping a toggle switch is a two-step action: selection and execution. It should reflect an action that triggers a state, never both at once.
Examples
Standalone
When using a standalone Switch
you should provide an aria-label
property value. As a form
component, it should have a label specified to guarantee accessibility.
With help text
With error text
With help and error texts
Disabled
Checked States
There are two checked states: `checked`, and `not checked`.
Multiple Switches
Oftentimes we need to render multiple switches and store the checked values in an array. It can be easily done using our `useSwitchState` hook, you just need to pass the hook return object to the switches `state` property and define a `value` for each `Switch`.
Usage
import { Switch } from '@vtex/admin-ui'
State
There are two ways of handling the state in the Switch.
checked and onChange
You can use the properties checked and onChange to handle if the Switch is checked and its values have changed.
useSwitchState
For convenience, we also provide a hook that already implements the state logic for you. It can be very handy if you have a group of switches and want to handle the states of each one. You should pass the hook return to the state property and also define a value for each Switch.
Props
Name | Type | Description | Required | Default |
---|---|---|---|---|
label | ReactNode | The component's label | ✅ | - |
helpText | ReactNode | Help text | 🚫 | - |
errorText | ReactNode | Error text | 🚫 | - |
error | boolean | Whether the switch contains an error or not | 🚫 | - |
checked | boolean | Switch's checked state. If present, it is used instead of state | 🚫 | - |
disabled | boolean | Defines if the Switch is disabled or not | 🚫 | - |
value | string, number | Switch's value is going to be used when multiple switches share the same state. Checking a switch with a value will add it to the state array | 🚫 | - |
state | SwtichState | Return of useSwitchState hook. You can also provide these props from your own state logic. | 🚫 | - |
csx | StyleProp | Defines component styles | 🚫 | {} |
The Switch component also supports all HTML props from the
<input />
HTML tag.
Do's
- Instant response that triggers a state, and require no further confirmation.
- List of independent items that represent different features or behaviors.
- Multually exclusive states, usually on/off type of decision.
- Use titles to group related controls.
- Choose words that are aligned with our ecommerce vocabulary.
- Write the current state of the control, to improve accessibility.
- Add descriptions if the control is critical, or complex.
- Lists of controls should be vertical for better scannability.
👉 For UX Writing guidelines, access https://uxwriting.vtex.com