Network
Switches toggle the selection of an item on and off. They are best used to adjust settings and other standalone options, and their effect should start immediately, without a save. Use them to:
- Toggle a single item on or off
- Immediately activate or deactivate something
Compared with the other selection controls:
- Switch or checkbox: A switch suits a setting or another standalone option that takes effect immediately. When several related options can be selected from a list, use checkboxes, which take up less space.
- Switch or radio button: A switch controls a single option that is either on or off, not a choice between two opposing options. Use switches, and not radio buttons, when the items of a list can be controlled independently.
import { Switch } from '@material-web/react'Basic switch
Use a Switch to toggle a single option on or off. Set defaultSelected on a switch that starts selected.
import { Switch } from '@material-web/react'
export default function Basic() {
return (
<div className="flex flex-col items-start gap-space-200 text-body-lg">
<Switch defaultSelected>
<span className="ps-space-200">Wi-Fi</span>
</Switch>
<Switch>
<span className="ps-space-200">Bluetooth</span>
</Switch>
</div>
)
}Set isDisabled to disable the switch: it cannot be toggled or focused. Set isReadOnly so that pressing the switch does not change its selection.
import { Switch } from '@material-web/react'
export default function Disabled() {
return (
<div className="flex flex-col items-start gap-space-200 text-body-lg">
<Switch isDisabled>
<span className="ps-space-200">Wi-Fi</span>
</Switch>
<Switch isDisabled defaultSelected icons="both">
<span className="ps-space-200">Bluetooth</span>
</Switch>
</div>
)
}Label
Write the label as the switch's children. Pressing the label toggles the switch. With no label text, set an aria-label. Keep the label short and direct: it describes what the switch does when it is on.
The switch adds no space before its label, so add it yourself, as ps-space-200 does in this example.
import { Switch } from '@material-web/react'
export default function WithLabel() {
return (
<>
<Switch defaultSelected className="text-body-lg">
<span className="ps-space-200">Dark mode</span>
</Switch>
<Switch aria-label="Airplane mode" />
</>
)
}The label takes the type style of the text around it. To set one, add its class to the switch or to an element around it, as in text-body-lg.
Icons
Set icons to choose the icons in the handle:
none(the default) shows no icon.selectedshows a check in the selected handle.bothalso shows an X in the unselected handle, which is then 24dp instead of 16dp.
The icons are decorative and are not part of the switch's name.
import { Switch } from '@material-web/react'
export default function Icons() {
return (
<div className="grid grid-cols-3 items-center justify-items-center gap-space-200">
<Switch aria-label="No icons, off" />
<Switch icons="selected" aria-label="Selected icon, off" />
<Switch icons="both" aria-label="Both icons, off" />
<Switch defaultSelected aria-label="No icons, on" />
<Switch icons="selected" defaultSelected aria-label="Selected icon, on" />
<Switch icons="both" defaultSelected aria-label="Both icons, on" />
<span className="text-label-md text-on-surface-variant">none</span>
<span className="text-label-md text-on-surface-variant">selected</span>
<span className="text-label-md text-on-surface-variant">both</span>
</div>
)
}Controlled
Control the selection with isSelected and onChange, which is called with the new selection. Without them, the switch keeps its own selection, starting from defaultSelected.
In this example, the switch is controlled, and its children are a function of its state that renders the supporting text for that state.
import { Switch } from '@material-web/react'
import { useState } from 'react'
export default function Controlled() {
const [isOn, setOn] = useState(true)
return (
<Switch icons="selected" isSelected={isOn} onChange={setOn} className="w-72">
{({ isSelected }) => (
<span className="flex flex-col ps-space-200">
<span className="text-body-lg">Wi-Fi</span>
<span className="text-body-md text-on-surface-variant">
{isSelected ? 'Public Campus Wi-Fi' : 'Off'}
</span>
</span>
)}
</Switch>
)
}Forms
Set a name to include a switch in a form. It is submitted with the form and reset with it. A selected switch submits its value, or on with no value, and an unselected switch submits nothing.
import { Button, Switch } from '@material-web/react'
import { useState } from 'react'
export default function Form() {
const [sent, setSent] = useState('Nothing sent yet')
return (
<form
className="flex flex-col items-start gap-space-200 text-body-lg"
onSubmit={(event) => {
event.preventDefault()
setSent(JSON.stringify(Object.fromEntries(new FormData(event.currentTarget))))
}}
>
<Switch name="newsletter" value="weekly" defaultSelected>
<span className="ps-space-200">Weekly newsletter</span>
</Switch>
<div className="flex gap-space-100">
<Button type="reset" variant="text">
Reset
</Button>
<Button type="submit">Save</Button>
</div>
<output className="text-body-sm text-on-surface-variant">{sent}</output>
</form>
)
}Set isRequired to require the switch to be selected. A required switch blocks its form from being submitted until then. See React Aria's Forms guide.
Note: isInvalid does not change how the switch looks.
In a list
In a list, a Switch in an item's slot does not select the item, as a Checkbox does. It is a separate control, so give it its own name and state.
import { List, ListItem, Switch } from '@material-web/react'
import { Text } from 'react-aria-components'
const settings = ['Wi-Fi', 'Bluetooth', 'Airplane mode']
export default function InList() {
return (
<List aria-label="Settings" className="w-90">
{settings.map((name) => (
<ListItem key={name} id={name} textValue={name}>
<Text slot="label">{name}</Text>
<Switch slot="trailing" aria-label={name} defaultSelected={name === 'Wi-Fi'} />
</ListItem>
))}
</List>
)
}Customization
Pass classes in className to restyle one switch. They go on its outermost element, an inline flex box aligned to the middle of its line, as do style and ref. inputRef is the ref of its input. See Styling for the classes, the states and the theme.
import { Switch } from '@material-web/react'
export default function Custom() {
return (
<div className="flex flex-col items-start gap-space-100 text-body-lg">
<Switch className="rounded-shape-full p-space-100 pe-space-300 has-hover:bg-surface-container">
<span className="ps-space-200">Highlighted on hover</span>
</Switch>
<Switch
defaultSelected
className="rounded-shape-full p-space-100 pe-space-300 selected:bg-secondary-container"
>
<span className="ps-space-200">Tinted when selected</span>
</Switch>
</div>
)
}- Color:
classNamedoes not reach the track and the handle. To change their colors, set the color roles they use. See Theme. - States: On a switch, the variants
selected:,invalid:,disabled:,read-only:andrequired:style those states. Hover, press and focus are reported on an element inside it, so use theirhas-*form, as inhas-hover:bg-surface-container. See States. - Functions:
classNameandstylecan be functions ofisSelected,isInvalid,isDisabled,isReadOnly,isRequiredandstate. To read hover, press and focus, pass a function as children. - Every switch: To restyle all the switches at once, change the theme.
Children as a function
Pass a function as children to render the label from the switch's state: isSelected, isHovered, isPressed, isFocused, isFocusVisible, isDisabled, isReadOnly, isInvalid, isRequired and state. isFocused is any focus, and isFocusVisible is keyboard focus only. The state's type is exported as SwitchRenderProps. The controlled example uses one. See Children as a function.
Use cases
Material lists what people should be able to do with assistive technology:
- Navigate to a switch with a keyboard or switch input
- Toggle the switch on and off
- Get appropriate feedback based on input type documented under Interaction & style
Interaction and style
- States: Hovering anywhere on the switch shows a state layer around the handle and darkens the handle, and the pointer is a hand. A press shows a ripple, and a press held for a moment grows the handle to 28dp, the cue Material uses to show that the handle is interactive. Keyboard focus shows a focus ring around the track, and a press with a mouse or touch does not.
- Touch target: A switch has a touch target of 52 by 48dp, centered on its track. Pressing its label toggles it too.
- Color contrast: In the light and dark schemes, at every contrast level, the track's edge keeps 3:1 contrast with the surface, the handle with the track, and an icon with the handle. Keep that contrast when you change the color roles they use.
- Density: Material advises against density that brings a switch's target under 48dp. A switch does not follow the density classes: it keeps its size and its target in a denser layout.
- Motion: With reduced motion, the handle and its state layer move and resize instantly.
- Forced colors: In forced colors, an unselected track is outlined in the system's text color, a selected track is filled with the system's highlight color, and a disabled switch and its label are grayed out.
- Right to left: The switch is mirrored in a right-to-left layout: the handle of an unselected switch is at the right.
Focus
- Each switch is a tab stop.
- A disabled switch cannot be focused, and Tab skips it. A read-only switch can still be focused.
Keyboard navigation
| Keys | Actions |
|---|---|
| Tab | Move the focus to a switch |
| Space or Enter | Turn the focused switch on or off |
- Enter does not submit the form the switch is in.
- To handle Enter yourself, call
preventDefaulton the event inonKeyDown. The switch then does not toggle.
Labeling elements
- A switch has the
switchrole, and is announced as on or off. - The label names the switch. With no label, set an
aria-label. - Where the label alone is ambiguous, Material advises a more descriptive name. Make the label more descriptive where you can, or set an
aria-labelthat includes it, such as Photo album access for a switch labeled Photo album. - The icons in the handle are hidden from assistive technology, and are not part of the name.
icons'none' | 'both' | 'selected'Default'none'The switch handle can contain an optional icon.
Icons can be used to visually emphasize the switch’s selection. The icon’s meaning should be clear and unambiguous to help the people understand whether switch is on or off.
- Without icons
- Icon on selected switch
- Icon on selected and unselected switch
Props of Switch (39)
classNameClassNameOrFunction<SwitchFieldRenderProps>Default'react-aria-SwitchField'The CSS className for the element. A function may be provided to compute the class based on component state.
inputRefRef<HTMLInputElement | null>A ref for the HTML input element.
formstringThe
<form>element to associate the input with. The value of this attribute must be the id of a<form>in the same document. See MDN.idstringThe element's unique identifier. See MDN.
aria-labelstringDefines a string value that labels the current element.
aria-labelledbystringIdentifies the element (or elements) that labels the current element.
aria-describedbystringIdentifies the element (or elements) that describes the object.
aria-detailsstringIdentifies the element (or elements) that provide a detailed, extended description for the object.
onClick(e: MouseEvent<FocusableElement>) => voidNot recommended – use
onPressinstead.onClickis an alias foronPressprovided for compatibility with other libraries.onPressprovides additional event details for non-mouse interactions.isDisabledbooleanWhether the input is disabled.
onPress(e: PressEvent) => voidHandler that is called when the press is released over the target.
onPressStart(e: PressEvent) => voidHandler that is called when a press interaction starts.
onPressEnd(e: PressEvent) => voidHandler that is called when a press interaction ends, either over the target or when the pointer leaves the target.
onPressChange(isPressed: boolean) => voidHandler that is called when the press state changes.
onPressUp(e: PressEvent) => voidHandler that is called when a press is released over the target, regardless of whether it started on the target or not.
autoFocusbooleanWhether the element should receive focus on render.
onFocus(e: FocusEvent<Target>) => voidHandler that is called when the element receives focus.
onBlur(e: FocusEvent<Target>) => voidHandler that is called when the element loses focus.
onFocusChange(isFocused: boolean) => voidHandler that is called when the element's focus status changes.
onKeyDown(e: KeyboardEvent) => voidHandler that is called when a key is pressed.
onKeyUp(e: KeyboardEvent) => voidHandler that is called when a key is released.
aria-controlsstringIdentifies the element (or elements) whose contents or presence are controlled by the current element.
namestringThe name of the input element, used when submitting an HTML form. See MDN.
valuestringThe value of the input element, used when submitting an HTML form. See MDN.
excludeFromTabOrderbooleanWhether to exclude the element from the sequential tab order. If true, the element will not be focusable via the keyboard by tabbing. This should be avoided except in rare scenarios where an alternative means of accessing the element or its functionality via the keyboard is available.
isSelectedbooleanWhether the element should be selected (controlled).
defaultSelectedbooleanWhether the element should be selected (uncontrolled).
onChange(isSelected: boolean) => voidHandler that is called when the element's selection state changes.
isReadOnlybooleanWhether the input can be selected but not changed by the user.
isInvalidbooleanWhether the input value is invalid.
isRequiredbooleanWhether user input is required on the input before form submission.
validate(value: boolean) => true | ValidationError | null | undefinedA function that returns an error message if a given value is invalid. Validation errors are displayed to the user when the form is submitted if
validationBehavior="native". For realtime validation, use theisInvalidprop instead.aria-errormessagestringIdentifies the element that provides an error message for the object.
validationBehavior'native' | 'aria'Default'native'Whether to use native HTML form validation to prevent form submission when the value is missing or invalid, or mark the field as required or invalid via ARIA.
styleCSSProperties | (values: SwitchFieldRenderProps & { defaultStyle: CSSProperties; }) => CSSProperties | undefinedThe inline style for the element. A function may be provided to compute the style based on component state.
renderDOMRenderFunction<'div', SwitchFieldRenderProps>Overrides the default DOM element with a custom render function. This allows rendering existing components with built-in styles and behaviors such as router links, animation libraries, and pre-styled components.
Requirements:
- You must render the expected element type (e.g. if
<button>is expected, you cannot render an<a>). - Only a single root DOM element can be rendered (no fragments).
- You must pass through props and ref to the underlying DOM element, merging with your own prop as appropriate.
- You must render the expected element type (e.g. if
slotstring | nullA slot name for the component. Slots allow the component to receive props from a parent component. An explicit
nullvalue indicates that the local props completely override all props received from a parent.childrenChildrenOrFunction<T>The children of the component. A function may be provided to alter the children based on component state.
refRef<HTMLDivElement>
Switch also takes the 69 attributes and events of the element it renders.