Switch
Switch is a UI element that let users choose between two states.
'use client';
import * as React from 'react';
import { Switch } from '@base_ui/react/Switch';
import classes from './styles.module.css';
export default function UnstyledSwitchIntroduction() {
return (
<div>
<Switch.Root
className={classes.root}
aria-label="Basic switch, on by default"
defaultChecked
>
<Switch.Thumb className={classes.thumb} />
</Switch.Root>
<Switch.Root
className={classes.root}
aria-label="Basic switch, off by default"
>
<Switch.Thumb className={classes.thumb} />
</Switch.Root>
<Switch.Root
className={classes.root}
aria-label="Disabled switch, on by default"
defaultChecked
disabled
>
<Switch.Thumb className={classes.thumb} />
</Switch.Root>
<Switch.Root
className={classes.root}
aria-label="Disabled switch, off by default"
disabled
>
<Switch.Thumb className={classes.thumb} />
</Switch.Root>
</div>
);
}
Installation
Base UI components are all available as a single package.
npm install @base_ui/react
Once you have the package installed, import the component.
import { Switch } from '@base_ui/react/Switch';
Anatomy
Switch is composed of two components:
<Switch.Root />
renders a<button>
.<Switch.Thumb />
renders a<span>
for providing a visual indicator.
Overriding default components
Use the render
prop to override the root or thumb component:
Accessibility
Ensure the Switch has an accessible name via a <label>
element.
API Reference
SwitchRoot
The foundation for building custom-styled switches.
Prop | Type | Default | Description |
---|---|---|---|
checked | bool | If true , the switch is checked. | |
className | union | Class names applied to the element or a function that returns them based on the component's state. | |
defaultChecked | bool | The default checked state. Use when the component is not controlled. | |
disabled | bool | false | If true , the component is disabled and can't be interacted with. |
inputRef | custom | Ref to the underlying input element. | |
name | string | Name of the underlying input element. | |
onCheckedChange | func | Callback fired when the checked state is changed. | |
readOnly | bool | false | If true , the component is read-only. Functionally, this is equivalent to being disabled, but the assistive technologies will announce this differently. |
render | union | A function to customize rendering of the component. | |
required | bool | false | If true , the switch must be checked for the browser validation to pass. |
SwitchThumb
Prop | Type | Default | Description |
---|---|---|---|
className | union | Class names applied to the element or a function that returns them based on the component's state. | |
render | union | A function to customize rendering of the component. |