Skip to content
Shaken UI
Sign in

Switch

Save

An on/off switch with a gliding thumb, two sizes, and an optional label and description for settings rows.

Category
Forms
Version
0.1.1
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Switch preview

Installation

npx @shakenui/cli add switch

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add switch --dry-run

Usage

switch-example.tsx
import { Switch } from "@/components/shaken/ui/switch";

export default function SwitchExample() {
  return (
    <div className="grid w-full max-w-md gap-8">
      <div className="divide-y divide-zinc-950/[0.07] rounded-xl border border-zinc-950/10 bg-white px-4 dark:divide-white/[0.08] dark:border-white/10 dark:bg-black">
        <Switch
          controlPosition="end"
          containerClassName="py-3.5"
          defaultChecked
          label="Stream tokens"
          description="Show the reply as it is written instead of all at once."
        />
        <Switch
          controlPosition="end"
          containerClassName="py-3.5"
          label="Pause before destructive tools"
          description="Deleting files or rows waits for an approval."
          defaultChecked
        />
        <Switch controlPosition="end" containerClassName="py-3.5" label="Share traces with support" disabled />
      </div>
      <div className="flex flex-wrap items-center gap-6">
        <Switch size="sm" label="Compact" />
        <Switch size="sm" defaultChecked label="Wrap lines" />
        <Switch aria-label="Auto-save" defaultChecked />
      </div>
    </div>
  );
}

API

PropTypeDefaultDescription
checked / defaultCheckedboolean—Controlled or initial state.
onCheckedChange(checked: boolean) => void—Called when the switch flips.
size"sm" | "md""md"16px or 20px tall.
labelReactNode—Text beside the switch. Clicking it flips the switch.
descriptionReactNode—A secondary line, linked with aria-describedby.
controlPosition"start" | "end""start"Put the switch before the text, or after it at the far edge for a settings row.
containerClassNamestring—Classes for the label wrapper. className styles the track.

Accessibility

  • Base UI renders role="switch" with aria-checked and a hidden native checkbox for forms.
  • The label names the switch through aria-labelledby and the description is linked with aria-describedby.
  • Space toggles the focused switch; the focus ring shows on keyboard focus only.
  • On and off differ in thumb position and track fill, not only color.
  • The thumb glides in 200ms; under reduced motion it moves without a transition.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/switch.tsxswitch
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/switch/0.1.1.json.

ui/switch.tsxShow
ui/switch.tsx
"use client";

import { Switch as BaseSwitch } from "@base-ui/react/switch";
import { type ReactNode, useId } from "react";

type ClassName<State> = string | ((state: State) => string | undefined) | undefined;

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

/** Prepends base classes while keeping Base UI's state-function form of className working. */
function withBase<State>(base: string, className: ClassName<State>) {
  return typeof className === "function" ? (state: State) => cx(base, className(state)) : cx(base, className);
}

const sizes = {
  sm: { track: "h-4 w-7", thumb: "size-3 data-[checked]:translate-x-3" },
  md: { track: "h-5 w-9", thumb: "size-4 data-[checked]:translate-x-4" },
} as const;

export type SwitchSize = keyof typeof sizes;

export interface SwitchProps extends BaseSwitch.Root.Props {
  /** `sm` (16px tall) for dense lists, `md` (20px) everywhere else. */
  size?: SwitchSize;
  /** Text beside the switch. Clicking it toggles the switch. */
  label?: ReactNode;
  /** A secondary line under the label, linked with `aria-describedby`. */
  description?: ReactNode;
  /**
   * `start` puts the switch before the text. `end` puts it after, pushed to the far edge,
   * the usual layout for a settings row.
   */
  controlPosition?: "start" | "end";
  /** Classes for the wrapper that holds the switch, label, and description. `className` styles the track. */
  containerClassName?: string;
}

/**
 * An on/off switch for settings that apply right away. The thumb glides across in 200ms with a
 * quick ease-out and the track fills; under reduced motion both change in place.
 */
export function Switch({
  size = "md",
  label,
  description,
  controlPosition = "start",
  containerClassName,
  className,
  "aria-describedby": describedBy,
  ...props
}: SwitchProps) {
  const id = useId();
  const labelId = `${id}-label`;
  const descriptionId = `${id}-description`;
  const hasText = label != null || description != null;

  const control = (
    <BaseSwitch.Root
      aria-labelledby={label != null ? labelId : undefined}
      aria-describedby={cx(description != null && descriptionId, describedBy) || undefined}
      className={withBase(
        cx(
          "group/switch relative inline-flex shrink-0 cursor-pointer items-center rounded-full p-0.5 outline-none",
          "after:absolute after:-inset-1.5 after:content-['']",
          sizes[size].track,
          "bg-zinc-950/[0.12] shadow-[inset_0_0_0_1px_rgb(0_0_0/0.04)] hover:bg-zinc-950/[0.18]",
          "dark:bg-white/[0.16] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.04)] dark:hover:bg-white/[0.22]",
          "data-[checked]:bg-zinc-950 data-[checked]:hover:bg-zinc-800 dark:data-[checked]:bg-white dark:data-[checked]:hover:bg-zinc-200",
          "data-[invalid]:shadow-[inset_0_0_0_1px_rgb(239_68_68)]",
          "transition-[background-color,box-shadow] duration-200 ease-out motion-reduce:transition-none",
          "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
          "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-45",
        ),
        className,
      )}
      {...props}
    >
      <BaseSwitch.Thumb
        className={cx(
          "block rounded-full bg-white shadow-[0_1px_2px_rgb(0_0_0/0.2),0_0_0_0.5px_rgb(0_0_0/0.04)]",
          "dark:data-[checked]:bg-black dark:data-[checked]:shadow-none",
          sizes[size].thumb,
          "transition-[translate,background-color] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
        )}
      />
    </BaseSwitch.Root>
  );

  if (!hasText) return control;

  const end = controlPosition === "end";
  return (
    <label
      className={cx(
        "group/item flex cursor-pointer items-start gap-3 has-[[data-disabled]]:cursor-not-allowed",
        end && "justify-between",
        containerClassName,
      )}
    >
      {end ? null : <span className="flex h-5 shrink-0 items-center">{control}</span>}
      <span className="grid min-w-0 gap-0.5 group-has-[[data-disabled]]/item:opacity-50">
        {label != null ? (
          <span id={labelId} className="text-sm leading-5 text-zinc-950 select-none dark:text-white">
            {label}
          </span>
        ) : null}
        {description != null ? (
          <span id={descriptionId} className="text-sm leading-5 text-zinc-500 dark:text-zinc-400">
            {description}
          </span>
        ) : null}
      </span>
      {end ? <span className="flex h-5 shrink-0 items-center">{control}</span> : null}
    </label>
  );
}