A switch allows a user to turn a setting on or off.
Vanilla CSS theme
This sets the
--tint CSS variable used by the Vanilla CSS examples.Theme
isDisabled
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 './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. See the Forms guide to learn more.
import {Switch} from './Switch';
import {Button} from './Button';
import {Form} from './Form';
<Form>
<Switch name="wifi">Wi-Fi</Switch>
<Button type="submit" style={{marginTop: 8}}>Submit</Button>
</Form>
API
<Switch>Label</Switch>
Switch
| Name | Type | |
|---|---|---|
inputRef | RefObject | |
| A ref for the HTML input element. | ||
defaultSelected | boolean | |
| Whether the Switch should be selected (uncontrolled). | ||
isSelected | boolean | |
| Whether the Switch should be selected (controlled). | ||
isDisabled | boolean | |
| Whether the input is disabled. | ||
isReadOnly | boolean | |
| Whether the input can be selected but not changed by the user. | ||
children | ChildrenOrFunction | |
| The children of the component. A function may be provided to alter the children based on component state. | ||
onChange | | |
| Handler that is called when the Switch's selection state changes. | ||
Default className: react-aria-Switch
| Render Prop | CSS Selector |
|---|---|
isSelected | CSS Selector: [data-selected]
|
| Whether the switch is selected. | |
isHovered | CSS Selector: [data-hovered]
|
| Whether the switch is currently hovered with a mouse. | |
isPressed | CSS Selector: [data-pressed]
|
| Whether the switch is currently in a pressed state. | |
isFocused | CSS Selector: [data-focused]
|
| Whether the switch is focused, either via a mouse or keyboard. | |
isFocusVisible | CSS Selector: [data-focus-visible]
|
| Whether the switch is keyboard focused. | |
isDisabled | CSS Selector: [data-disabled]
|
| Whether the switch is disabled. | |
isReadOnly | CSS Selector: [data-readonly]
|
| Whether the switch is read only. | |
state | CSS Selector: — |
| State of the switch. | |