Skip to content
All components
Forms

Switch

Turn a single setting on or off with an immediate effect.

An instant-effect toggle that uses the shared elevation token.

Installation

tdpxl is not an npm dependency of your app. The @tdpxl/cli command (not published to npm yet) copies the source into your project, with the registry items and npm packages it imports.

npx @tdpxl/cli add switch

Then import it from @/components/ui/switch. New project? Start with the installation guide.

Examples

Each example is one branch of the official demo, rendered in its own frame. The code is that branch as you would write it, with imports pointing at the default install paths.

Checked

Show an enabled on/off setting in its checked state. Preserves the complete example's required parts, labels and providers. The example's local state remains owned by that composition.

"use client"

import * as React from "react"

import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

export function SwitchChecked() {
  const id = React.useId()

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-2">
        <Switch id="switch-demo-dark" defaultChecked />
        <Label htmlFor="switch-demo-dark">Follow system theme</Label>
      </div>
    </div>
  )
}

Unchecked

Show an enabled on/off setting in its unchecked state. Preserves the complete example's required parts, labels and providers. The example's local state remains owned by that composition.

"use client"

import * as React from "react"

import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

export function SwitchUnchecked() {
  const id = React.useId()

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-2">
        <Switch id="switch-demo-beta" />
        <Label htmlFor="switch-demo-beta">Join the beta channel</Label>
      </div>
    </div>
  )
}

Disabled

Inspect the unavailable control using its real disabled semantics. Preserves the complete example's required parts, labels and providers. The example's local state remains owned by that composition.

"use client"

import * as React from "react"

import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

export function SwitchDisabled() {
  const id = React.useId()

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-2">
        <Switch id="switch-demo-off" disabled />
        <Label htmlFor="switch-demo-off">Disabled</Label>
      </div>
    </div>
  )
}

With description

Place a label and description beside a switch whose change applies immediately. Preserves the complete example's required parts, labels and providers. The example's local state remains owned by that composition.

"use client"

import * as React from "react"

import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

export function SwitchWithDescription() {
  const id = React.useId()

  return (
    <div className="flex flex-col gap-6">
      <div className="flex w-full max-w-sm items-start justify-between gap-4">
        <div className="flex flex-col gap-1">
          <Label htmlFor={`${id}-autosave`}>Autosave drafts</Label>
          <p id={`${id}-autosave-hint`} className="text-paragraph-sm text-sub-600">
            Saves your changes every few seconds while you edit.
          </p>
        </div>
        <Switch id={`${id}-autosave`} defaultChecked aria-describedby={`${id}-autosave-hint`} />
      </div>
    </div>
  )
}

Settings group

Group related settings under a legend, each with its own description. Preserves the complete example's required parts, labels and providers. The example's local state remains owned by that composition.

"use client"

import * as React from "react"

import { FieldLegend, FieldSet } from "@/components/ui/field"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

const notificationSettings = [
  { key: "mentions", label: "Mentions", hint: "When someone mentions you in a comment.", on: true },
  { key: "assigned", label: "Assigned to me", hint: "When a task is assigned to you.", on: true },
  { key: "digest", label: "Weekly digest", hint: "A summary of activity every Monday.", on: false },
]

export function SwitchSettingsGroup() {
  const id = React.useId()

  return (
    <div className="flex flex-col gap-6">
      <FieldSet className="w-full max-w-sm">
        <FieldLegend>Email notifications</FieldLegend>
        <div className="flex flex-col gap-4">
          {notificationSettings.map((setting) => (
            <div key={setting.key} className="flex items-start justify-between gap-4">
              <div className="flex flex-col gap-1">
                <Label htmlFor={`${id}-${setting.key}`}>{setting.label}</Label>
                <p id={`${id}-${setting.key}-hint`} className="text-paragraph-sm text-sub-600">
                  {setting.hint}
                </p>
              </div>
              <Switch
                id={`${id}-${setting.key}`}
                defaultChecked={setting.on}
                aria-describedby={`${id}-${setting.key}-hint`}
              />
            </div>
          ))}
        </div>
      </FieldSet>
    </div>
  )
}

Disabled with reason

Show a locked setting and explain who can change it. Preserves the complete example's required parts, labels and providers. The example's local state remains owned by that composition.

"use client"

import * as React from "react"

import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

export function SwitchDisabledWithReason() {
  const id = React.useId()

  return (
    <div className="flex flex-col gap-6">
      <div className="flex w-full max-w-sm items-start justify-between gap-4">
        <div className="flex flex-col gap-1">
          <Label htmlFor={`${id}-sso`}>Require single sign-on</Label>
          <p id={`${id}-sso-hint`} className="text-paragraph-sm text-sub-600">
            Managed by your organization. Ask an administrator to change it.
          </p>
        </div>
        <Switch id={`${id}-sso`} defaultChecked disabled aria-describedby={`${id}-sso-hint`} />
      </div>
    </div>
  )
}

Sizes

Compare the sm and md switch sizes. Both sizes keep a pointer target at least 24px tall.

"use client"

import * as React from "react"

import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

export function SwitchSizes() {
  const id = React.useId()

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-3">
        <div className="flex items-center gap-2">
          <Switch id={`${id}-size-sm`} size="sm" defaultChecked />
          <Label htmlFor={`${id}-size-sm`}>Small</Label>
        </div>
        <div className="flex items-center gap-2">
          <Switch id={`${id}-size-md`} defaultChecked />
          <Label htmlFor={`${id}-size-md`}>Medium</Label>
        </div>
      </div>
    </div>
  )
}

Slim

Use the slim switch with a thin track and outlined thumb. variant="slim" changes only the look; keyboard, labels and the 24px target are unchanged.

"use client"

import * as React from "react"

import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

export function SwitchSlim() {
  const id = React.useId()

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-3">
        <div className="flex items-center gap-2">
          <Switch id={`${id}-slim-sm`} variant="slim" size="sm" defaultChecked />
          <Label htmlFor={`${id}-slim-sm`}>Show weekends</Label>
        </div>
        <div className="flex items-center gap-2">
          <Switch id={`${id}-slim-md`} variant="slim" />
          <Label htmlFor={`${id}-slim-md`}>Compact rows</Label>
        </div>
        <div className="flex items-center gap-2">
          <Switch id={`${id}-slim-off`} variant="slim" disabled />
          <Label htmlFor={`${id}-slim-off`}>Disabled</Label>
        </div>
      </div>
    </div>
  )
}

API reference

Generated from the component's TypeScript signatures. Inherited DOM and primitive props are listed separately.

Switch

Represent a boolean setting with immediate effect.

Switch props
PropTypeDefaultDescription
inputMode"search" | "text" | "none" | "tel" | "url" | "email" | "numeric" | "decimal" | undefined—Hints at the type of data that might be entered by the user while editing the element or its contents
aria-describedbystring | undefined—Identifies the element (or elements) that describes the object.
aria-invalidboolean | "false" | "true" | "grammar" | "spelling" | undefined—Indicates the entered value does not conform to the format expected by the application.
aria-labelstring | undefined—Defines a string value that labels the current element.
aria-labelledbystring | undefined—Identifies the element (or elements) that labels the current element.
childrenReact.ReactNode—Represents all of the things React can render.
size"sm" | "md" | undefined"md"Track size: sm or md. Both keep a pointer target at least 24px tall. Defaults to md.
variant"default" | "slim" | undefined"default"default places the thumb inside the track; slim uses a thin track with a larger outlined thumb. Defaults to default.
Inherited props (22)
Switch inherited props
PropTypeDefaultDescription
checkedboolean | undefined—Current checked state. Apply the requested value from onCheckedChange when the parent owns this state.
defaultCheckedboolean | undefined—Initial checked state for a control supporting uncontrolled selection. Inherited DOM typing does not give a layout wrapper checkbox behavior.
requiredboolean | undefined—Mark this control as required using its native or primitive semantics. Consumers own contextual validation feedback.
onCheckedChange((checked: boolean) => void) | undefined—Receive the next checked state. Apply it to checked when the parent controls the component.
formstring | undefined—ID of the form associated with this control, including when it is rendered outside that form element.
classNamestring | undefined—Additional classes for this part. Preserve contrast, visible focus and responsive content when adapting styles.
defaultValuestring | number | readonly string[] | undefined—Initial value for a control supporting uncontrolled state. Inherited DOM typing alone does not give a layout wrapper input behavior.
autoFocusboolean | undefined—Request automatic focus when the element mounts or the primitive opens, according to its source behavior. Choose initial focus deliberately in context.
idstring | undefined—Stable DOM identifier used by labels, descriptions or other explicit associations.
roleReact.AriaRole | undefined—Semantic role appropriate to the rendered element. Preserve required relationships and keyboard behavior.
onFocusReact.FocusEventHandler<HTMLButtonElement> | undefined—Receive the native focus event. Preserve the component's existing keyboard and focus behavior.
onBlurReact.FocusEventHandler<HTMLButtonElement> | undefined—Receive the native blur event when focus leaves this control.
onChangeReact.ChangeEventHandler<HTMLButtonElement, Element> | undefined—Receive the native change event; read the actual control value or checked state from its event target.
onKeyDownReact.KeyboardEventHandler<HTMLButtonElement> | undefined—Receive keyboard events. Preserve built-in keyboard behavior unless deliberately implementing an accessible alternative.
onClickReact.MouseEventHandler<HTMLButtonElement> | undefined—Receive activation events. The consumer owns the action performed and its result.
onSelectReact.ReactEventHandler<HTMLButtonElement> | undefined—Handle the selection event defined by this part's source signature. DOM text-selection events differ from menu or command activation callbacks.
asChildboolean | undefined—Merge this part into one child instead of its default element. Preserve that child's semantics, ref support and accessibility attributes.
disabledboolean | undefined—Make the supported control unavailable through its native or primitive disabled semantics. This does not disable arbitrary child links.
namestring | undefined—Name used by the control's form submission or primitive form integration.
type"button" | "submit" | "reset" | undefined—Native element or primitive mode defined by the source union. Choose a supported value; its meaning depends on the component.
valuestring | number | readonly string[] | undefined—Current value in the shape defined by the source type. For controlled interactive inputs, apply updates from the change callback.
refReact.Ref<HTMLButtonElement> | undefined—Allows getting a ref to the component instance. Once the component unmounts, React will set ref.current to null (or call the ref with null if you passed a callback ref).

Accessibility & usage

From registry/ui/switch.meta.json (authored guidance; human review may still be pending). Behavior is checked by Storybook tests, not certified here.

When to use

  • Settings that apply as soon as they change, such as notifications, autosave or visibility.
  • Setting rows that pair a label and description with the control at the end.

When not to use

  • Choices that only take effect after a submit button; use a checkbox.
  • More than two states, or options whose meaning is not on/off.
  • Triggering a one-time action; use a button.

Anatomy

Switch
The Radix switch button (role=switch) with checked, defaultChecked, onCheckedChange, disabled, required and name. size is sm or md (default); variant is default (thumb inside the track) or slim (thin track, larger outlined thumb). All keep a pointer target at least 24px tall.
Thumb
The moving knob; its position shows the state alongside the track color. It moves toward the inline end when checked, including right-to-left layouts.
Label and description
A Label with htmlFor, plus an optional description referenced from aria-describedby.

Keyboard & interaction

  • Space and Enter toggle the focused switch; clicking its label toggles it too.
  • The state is exposed as aria-checked and announced as on or off.
  • Keyboard focus shows an outline offset from the track.
  • Apply the change immediately; if it needs a request, keep the new state, show progress nearby and revert with an explanation if it fails.
  • Disabled switches leave the Tab order; explain why in the description.

Responsive behavior

  • The track looks 32x20 CSS px but its hit area is 32x24 CSS px (WCAG 2.5.8); an associated label makes the whole row a target. Keep the hit area if you resize the track.
  • In setting rows put the label and description first and the switch at the end of the row; the text wraps, the switch never shrinks.
  • On narrow screens keep the switch on the same row as its label; do not push it under a long description.

Content guidelines

  • Label names the setting in positive terms ('Autosave drafts'), not 'Enable' or 'On/Off'.
  • Description states the effect or a constraint ('Saves your changes every few seconds').
  • For a locked setting, say who can change it ('Managed by your organization').

Alternatives

  • Checkbox — An option that is confirmed when the form is submitted.
  • Radio group — Two or more named, mutually exclusive options.
  • Toggle — A pressed state for a formatting or view option in a toolbar.
  • Button — A one-time action.

Resources