For the complete documentation index, see llms.txt. Markdown variants are available by appending .md to any URL or sending an Accept: text/markdown header. An agent skill is available at /.well-known/agent-skills/site-skill.md.
FrakmentFrakment

Switch

A toggle control for a single on/off setting.

Web
Frakment
switch.tsx
"use client";

import * as React from "react";

import {
  getTransition,
  parseMotion,
  useMotionGuard,
  useReducedMotion,
} from "@/lib/motion";
import { cn } from "@/lib/utils";

type SwitchSize = "sm" | "default";

type SwitchProps = Omit<
  React.ComponentProps<"button">,
  "onChange" | "role" | "aria-checked" | "type"
> & {
  checked?: boolean;
  defaultChecked?: boolean;
  disabled?: boolean;
  motion?: string;
  onCheckedChange?: (checked: boolean) => void;
  size?: SwitchSize;
};

function Switch({
  checked: checkedProp,
  className,
  defaultChecked = false,
  disabled = false,
  motion,
  onClick,
  onCheckedChange,
  ref,
  size = "default",
  ...props
}: SwitchProps) {
  const isControlled = checkedProp !== undefined;
  const [uncontrolledChecked, setUncontrolledChecked] =
    React.useState(defaultChecked);
  const checked = isControlled ? checkedProp : uncontrolledChecked;
  const reduce = useReducedMotion();
  const internalRef = React.useRef<HTMLButtonElement | null>(null);

  const setRef = React.useCallback(
    (node: HTMLButtonElement | null) => {
      internalRef.current = node;
      if (typeof ref === "function") {
        ref(node);
      } else if (ref) {
        (ref as React.MutableRefObject<HTMLButtonElement | null>).current =
          node;
      }
    },
    [ref]
  );

  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    onClick?.(event);
    if (event.defaultPrevented || disabled) {
      return;
    }
    const next = !checked;
    if (!isControlled) {
      setUncontrolledChecked(next);
    }
    onCheckedChange?.(next);
  };

  const motionValue = motion;
  const thumbStyle: React.CSSProperties = {};
  if (reduce) {
    thumbStyle.transition = "none";
  } else if (motionValue !== undefined) {
    const transition = getTransition(parseMotion(motionValue));
    if (transition) {
      thumbStyle.transition = transition;
    }
  }

  const motionEnabled = motionValue !== undefined && !reduce;
  const styleFingerprint = JSON.stringify(thumbStyle);
  const yielded = useMotionGuard(
    internalRef as React.RefObject<HTMLElement | null>,
    motionEnabled,
    styleFingerprint
  );
  if (yielded && !reduce) {
    thumbStyle.transition = "none";
  }

  return (
    <button
      aria-checked={checked}
      className={cn(
        "peer group/switch focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-input/80 relative inline-flex shrink-0 items-center rounded-full border border-transparent outline-none group-has-[:focus-visible]/field-label:border-transparent group-has-[:focus-visible]/field-label:ring-0 after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:ring-3 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:ring-3 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px]",
        className
      )}
      data-size={size}
      data-slot="switch"
      data-state={checked ? "checked" : "unchecked"}
      disabled={disabled}
      onClick={handleClick}
      ref={setRef}
      role="switch"
      type="button"
      {...props}
    >
      <span
        className={cn(
          "bg-background dark:data-[state=checked]:bg-primary-foreground dark:data-[state=unchecked]:bg-foreground pointer-events-none block rounded-full ring-0",
          "group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3",
          "transition-transform group-data-[size=default]/switch:data-[state=checked]:translate-x-[calc(100%-2px)] group-data-[size=default]/switch:data-[state=unchecked]:translate-x-0",
          "group-data-[size=sm]/switch:data-[state=checked]:translate-x-[calc(100%-2px)] group-data-[size=sm]/switch:data-[state=unchecked]:translate-x-0"
        )}
        data-slot="switch-thumb"
        data-state={checked ? "checked" : "unchecked"}
        style={thumbStyle}
      />
    </button>
  );
}

export { Switch };

Switch is a native toggle button with role="switch" and aria-checked, styled with Frakment tokens. Pair it with Label (via htmlFor) for accessible click-through, or wrap it in Field for larger settings rows.

Installation

Usage

switch.tsx
import { Switch } from "@/components/ui/switch";
tsx
<Switch />

Examples

Checked

Use defaultChecked for uncontrolled initial state, or checked / onCheckedChange for a controlled switch.

switch-checked.tsx
"use client";

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

export function SwitchChecked() {
  return (
    <div className="flex items-center gap-2">
      <Switch defaultChecked id="s-wifi" />
      <Label htmlFor="s-wifi">Wi-Fi</Label>
    </div>
  );
}

Disabled

switch-disabled.tsx
"use client";

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

export function SwitchDisabled() {
  return (
    <div className="flex items-center gap-2">
      <Switch disabled id="s-dis" />
      <Label className="opacity-50" htmlFor="s-dis">
        Disabled
      </Label>
    </div>
  );
}

With description

Compose with Field and FieldContent (see Field docs) — or lay out manually as below.

Focused settings sync between devices.

switch-with-description.tsx
"use client";

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

export function SwitchWithDescription() {
  return (
    <div className="flex w-full max-w-sm items-start justify-between gap-4">
      <div className="flex flex-col gap-1">
        <Label htmlFor="s-sync">Share across devices</Label>
        <p className="text-muted-foreground text-sm">
          Focused settings sync between devices.
        </p>
      </div>
      <Switch id="s-sync" />
    </div>
  );
}

Settings row

Notifications

Get an email on replies.

switch-settings-row.tsx
import { Switch } from "@/components/ui/switch";

export function SwitchSettingsRow() {
  return (
    <div className="mx-auto flex w-full max-w-sm items-center justify-between">
      <div>
        <p className="text-sm font-medium">Notifications</p>
        <p className="text-muted-foreground text-xs">
          Get an email on replies.
        </p>
      </div>
      <Switch defaultChecked />
    </div>
  );
}

Feature flag

New editor

Try the beta experience.

switch-feature-flag.tsx
import { Switch } from "@/components/ui/switch";

export function SwitchFeatureFlag() {
  return (
    <div className="mx-auto flex w-full max-w-sm items-center justify-between">
      <div>
        <p className="text-sm font-medium">New editor</p>
        <p className="text-muted-foreground text-xs">
          Try the beta experience.
        </p>
      </div>
      <Switch />
    </div>
  );
}

Anatomy

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

export function SwitchAnatomy() {
  return (
    <div className="flex items-center gap-3">
      <Switch defaultChecked id="a" />
      <label className="text-sm" htmlFor="a">
        On
      </label>
      <Switch id="b" />
      <label className="text-sm" htmlFor="b">
        Off
      </label>
    </div>
  );
}
  • Track — 32×18 pill, bg-input off, bg-primary on
  • Thumb — 16px circle that slides 14px between ends
  • Label — separate element, linked with htmlFor

API Reference

Switch

Renders a native <button> with role="switch" and aria-checked.

PropTypeDefaultDescription
checkedboolean—Controlled state.
defaultCheckedboolean—Uncontrolled initial state.
onCheckedChange(checked: boolean) => void—Fires on toggle.
disabledboolean—Removes the switch from the tab order.
size
smdefault
—Track and thumb dimensions.
motionstring—CSS transition override for the thumb; e.g. 200 ease-out or 300 cubic-bezier(...). Respects prefers-reduced-motion.

Controlled

tsx
const [checked, setChecked] = React.useState(false);
<Switch checked={checked} onCheckedChange={setChecked} />

States

StateHow
Offdefault
Onchecked or defaultChecked
Disableddisabled prop

Keyboard

KeyAction
SpaceToggle
EnterToggle

Data Attributes

AttributeValues
data-slotswitch, switch-thumb
data-statechecked | unchecked
data-sizedefault | sm

Motion

The thumb slides with a CSS transition-transform by default. Override with motion without editing the file:

tsx
<Switch motion="300 cubic-bezier(0.34, 1.56, 0.64, 1)" />
ValueResult
omittedTailwind default transition
"200"200ms ease-in-out
"300 cubic-bezier(...)"300ms custom easing
"off"no transition

When prefers-reduced-motion is set, the transition is disabled regardless of the value. Third-party animation libraries that write inline styles to the thumb automatically suppress the internal CSS transition.

Accessibility

  • Renders <button role="switch"> with aria-checked managed automatically. Do not add role manually.
  • Pair with a <Label> or FieldLabel using htmlFor.
  • The visual state (on/off) is conveyed by position and color. The accessible state is conveyed by aria-checked.
  • disabled removes the switch from the tab order.

Best Practices

  • Use Switch for instant toggles. If the change requires a Save button, use Checkbox.
  • Do not use "On" / "Off" labels. The state is visible in the track.
  • Keep the label short. A phrase, not a sentence.
  • Group related switches under a heading rather than scattering them.
  • Do not use Switch for a destructive action. Use a Dialog confirmation.
  • Label — paired text
  • Field — settings row layout