Switches allow users to turn an individual option on or off. They are usually used to activate or deactivate a specific setting.
Selection
Use the isSelected or defaultSelected prop to set the selection state, and onChange to handle selection changes.
High power mode active.
import {Switch} from '@react-spectrum/s2/Switch';
import {useState} from 'react';
function Example(props) {
let [selected, setSelection] = useState(false);
return (
<>
<Switch
{...props}
isSelected={selected}
onChange={setSelection}
>
Low power mode
</Switch>
<p>{selected ? 'Low' : 'High'} power mode active.</p>
</>
);
}
Forms
Use the name and value props to submit the switch to the server. Set the isRequired prop to validate the user selects the switch, or implement custom client or server-side validation. See the Forms guide to learn more.
import {Switch} from '@react-spectrum/s2/Switch';
import {Button} from '@react-spectrum/s2/Button';
import {Form} from '@react-spectrum/s2/Form';
<Form>
<Switch
name="two-factor"
isRequired
description="Your organization requires two-factor authentication.">
Two-factor authentication
</Switch>
<Button type="submit">Submit</Button>
</Form>
API
| Name | Type | Default |
|---|---|---|
children | ReactNode | Default: — |
inputRef | RefObject | Default: — |
A ref for the HTML input element. | ||
defaultSelected | boolean | Default: — |
Whether the element should be selected (uncontrolled). | ||
isSelected | boolean | Default: — |
Whether the element should be selected (controlled). | ||
isDisabled | boolean | Default: — |
Whether the input is disabled. | ||
isReadOnly | boolean | Default: — |
Whether the input can be selected but not changed by the user. | ||
styles | StylesProp | Default: — |
Spectrum-defined styles, returned by the | ||
size | 'S'
| 'M'
| 'L'
| 'XL' | Default: 'M'
|
The size of the Switch. | ||
isEmphasized | boolean | Default: — |
Whether the Switch should be displayed with an emphasized style. | ||
onChange | | Default: — |
Handler that is called when the element's selection state changes. | ||