Skip to main content

Overview

Switch provides a binary control that users can toggle on or off. It’s similar to a checkbox but styled to look like a physical toggle switch.

Features

  • Can be controlled or uncontrolled
  • Full keyboard navigation
  • Works inside forms
  • Accessible by default with proper ARIA attributes

Installation

npm install @radix-ui/react-switch

Anatomy

import * as Switch from '@radix-ui/react-switch';

export default () => (
  <Switch.Root>
    <Switch.Thumb />
  </Switch.Root>
);

API Reference

Root

Contains all the switch component parts. An input will also render when used within a form to ensure events propagate correctly.
checked
boolean
The controlled checked state of the switch.
defaultChecked
boolean
The checked state when initially rendered (uncontrolled).
onCheckedChange
(checked: boolean) => void
Event handler called when the checked state changes.
disabled
boolean
When true, prevents the user from interacting with the switch.
required
boolean
When true, indicates that the user must check the switch before the form can be submitted.
name
string
The name of the switch. Submitted with its owning form as part of a name/value pair.
value
string
default:"'on'"
The value given as data when submitted with a name.
asChild
boolean
default:"false"
Change the default rendered element for the one passed as a child.

Thumb

The thumb that is used to visually indicate whether the switch is on or off.
asChild
boolean
default:"false"
Change the default rendered element for the one passed as a child.

Example

import * as Switch from '@radix-ui/react-switch';
import './styles.css';

export default () => (
  <form>
    <div style={{ display: 'flex', alignItems: 'center' }}>
      <label className="Label" htmlFor="airplane-mode" style={{ paddingRight: 15 }}>
        Airplane mode
      </label>
      <Switch.Root className="SwitchRoot" id="airplane-mode">
        <Switch.Thumb className="SwitchThumb" />
      </Switch.Root>
    </div>
  </form>
);

Accessibility

Keyboard Interactions

  • Space - Toggles the switch.

Data Attributes

Root
  • [data-state] - “checked” or “unchecked”
  • [data-disabled] - Present when disabled
Thumb
  • [data-state] - “checked” or “unchecked”
  • [data-disabled] - Present when disabled

Build docs developers (and LLMs) love