Switch
Switch is a UI element that let users choose between two states.
Installation
Base UI components are all available as a single package.
npm install @base-ui-components/react
Once you have the package installed, import the component.
import { Switch } from '@base-ui-components/react/Switch';
Anatomy
Switch is composed of two components:
<Switch.Root />
renders a<button>
.<Switch.Thumb />
renders a<span>
for providing a visual indicator.
<Switch.Root>
<Switch.Thumb />
</Switch.Root>
Overriding default components
Use the render
prop to override the root or thumb component:
<Switch.Root render={(props) => <MyCustomSwitch {...props} />}>
<Switch.Thumb render={(props) => <MyCustomThumb {...props} />} />
</Switch.Root>
Accessibility
Ensure the Switch has an accessible name via a <label>
element.
<Switch.Root id="my-switch">
<Switch.Thumb />
</Switch.Root>
<label htmlFor="my-switch">
My label
</label>
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 | false | The default checked state. Use when the component is uncontrolled. |
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. |