Switch
Switches are UI elements that let users choose between two states—most commonly on/off.
Introduction
The Switch component provides users with a switch for toggling between two mutually exclusive states.
Component
import { Switch } from '@mui/base/Switch';
Anatomy
The Switch component is composed of a root <span>
that houses three interior slots—a track, a thumb, and an input:
<span class="base-Switch-root">
<span class="base-Switch-track"></span>
<span class="base-Switch-thumb"></span>
<input type="checkbox" class="base-Switch-input" />
</span>
Custom structure
Use the slots
prop to override the root or any other interior slot:
<Switch slots={{ root: 'div', track: 'div' }} />
Use the slotProps
prop to pass custom props to internal slots.
The following code snippet applies a CSS class called my-thumb
to the thumb slot:
<Switch slotProps={{ thumb: { className: 'my-thumb' } }} />
Usage with TypeScript
In TypeScript, you can specify the custom component type used in the slots.root
as a generic parameter of the unstyled component.
This way, you can safely provide the custom root's props directly on the component:
<Switch<typeof CustomComponent> slots={{ root: CustomComponent }} customProp />
The same applies for props specific to custom primitive elements:
<Switch<'input'> slots={{ root: 'input' }} autoFocus={true} />
Hook
import { useSwitch } from '@mui/base/useSwitch';
The useSwitch
hook lets you apply the functionality of a Switch to a fully custom component.
It returns props to be placed on the custom component, along with fields representing the component's internal state.
Hooks do not support slot props, but they do support customization props.
Basic example
Accessibility
To make the Switch component accessible, you should ensure that the corresponding labels reflect the Switch's current state.