Switch

An on/off switch for settings that apply right away.

Use a switch when the change takes effect immediately, and a checkbox when it’s applied with the rest of a form.

Preview
basic.tsx
import { Label } from "~/components/ui/label"
import { Switch } from "~/components/ui/switch"

export default function Example() {
  return (
    <div className="grid gap-md">
      <Label>
        <Switch defaultChecked />
        Wi-Fi
      </Label>
      <Label>
        <Switch />
        Airplane mode
      </Label>
    </div>
  )
}

Dependencies

What it's built from and what's built from it in Base, read from the imports in its source.

UsesNothing else in the system.
Used byNothing yet.
Packages @ui-sdk/core@0.1.0-beta.20@ui-sdk/react@0.1.0-beta.20

Installation

Set the project up for Base once first, as Getting started shows. Then add it with the CLI, or by hand.

With the CLI

terminal
npx shadcn@latest add https://design.zepez.dev/r/base/switch.json

Manually

Install its packages:

terminal
npm install @ui-sdk/core@0.1.0-beta.20 @ui-sdk/react@0.1.0-beta.20

Then copy the source:

components/ui/switch.tsx
import {
  Switch as SwitchPrimitive,
  SwitchThumb as SwitchThumbPrimitive,
} from "@ui-sdk/react/switch"
import type * as React from "react"

import { cnState } from "~/lib/utils"

/**
 * An on/off switch with its thumb built in, filled like the system's inputs.
 * Wrap it in a `Label` with its text, or name it with `aria-label`.
 */
function Switch({
  className,
  children,
  onKeyDown,
  ...props
}: React.ComponentProps<typeof SwitchPrimitive>) {
  return (
    <SwitchPrimitive
      // Enter toggles it too, as the ARIA switch pattern allows; ui-sdk leaves Enter to submit
      // the form, as a checkbox does. Calling preventDefault skips ui-sdk's own Enter handling.
      onKeyDown={(event) => {
        onKeyDown?.(event)
        if (event.defaultPrevented || event.key !== "Enter" || event.nativeEvent.isComposing) return
        event.preventDefault()
        event.currentTarget.click()
      }}
      className={cnState(
        [
          "peer inline-flex h-[1.125rem] w-8 shrink-0 cursor-pointer items-center rounded-lg border border-transparent bg-input/90 p-px",
          "transition-[background-color,box-shadow] duration-150",
          "outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30",
          "data-checked:bg-primary",
          "aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20",
          "data-disabled:cursor-not-allowed data-disabled:opacity-50",
        ].join(" "),
        className,
      )}
      {...props}
    >
      {children ?? <SwitchThumb />}
    </SwitchPrimitive>
  )
}

/** The sliding thumb. */
function SwitchThumb({ className, ...props }: React.ComponentProps<typeof SwitchThumbPrimitive>) {
  return (
    <SwitchThumbPrimitive
      className={cnState(
        [
          "pointer-events-none block size-3.5 rounded-lg bg-background shadow-sm",
          "transition-[translate] duration-150 motion-reduce:transition-none",
          "data-checked:translate-x-3.5 data-checked:bg-primary-foreground rtl:data-checked:-translate-x-3.5",
        ].join(" "),
        className,
      )}
      {...props}
    />
  )
}

export { Switch, SwitchThumb }

API reference

Generated from Base's types. Props marked ours are added here; the rest come from the ui-sdk part it wraps. Every part also accepts its element's native attributes.

Switch

An on/off switch with its thumb built in, filled like the system's inputs. Wrap it in a Label with its text, or name it with aria-label.

checked

Whether it's checked. Pass it to control the checkbox.

Type boolean

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: SwitchState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: SwitchState) => string)

controller

Toggles it from anywhere. Create one with createSwitchController().

Type { toggle: (details?: CheckboxChangeOptions) => boolean; getChecked: () => boolean; setChecked: (checked: boolean, details?: CheckboxChangeOptions) => boolean; focus: () => void; }

debug

Logs every state change with its reason to the console, in development builds.

Type boolean

defaultChecked

Whether it's checked at first, when uncontrolled. A form reset returns to it.

Type boolean · Default false

disabled

Disables it like a native control: it can't be focused or changed, and isn't submitted.

Type boolean

form

The id of a form to belong to, when it isn't inside that form.

Type string

name

The name it submits under. Without one, it submits nothing.

Type string

onCheckedChange

Runs when a user or a form reset wants to change it. details.reason says why, and details.cancel() stops it.

Type (checked: boolean, details: ChangeDetails<CheckboxCheckedChangeReason>) => void

readOnly

Keeps it focusable and submitted, but stops changes.

Type boolean

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<SwitchState>

required

Blocks form submission until it's checked, with the browser's own message.

Type boolean

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: SwitchState) => CSSProperties)

value

What it submits while checked.

Type string · Default "on"

SwitchThumb

The sliding thumb.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: NoInfer<SwitchState>) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: NoInfer<SwitchState>) => string)

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<NoInfer<SwitchState>>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: NoInfer<SwitchState>) => CSSProperties)