Switch field

An accessible on/off switch (role="switch" with aria-checked) and a SwitchField that pairs it with a clickable label and a description through aria-labelledby and aria-describedby. Controlled or uncontrolled, two sizes, disabled state, a reduced-motion-aware thumb, and a hidden input so it submits with forms like a checkbox.

Forms & inputsComponentTailwind v4

Source

"use client";

import { forwardRef, useId, useState, type ButtonHTMLAttributes, type ReactNode } from "react";
import { cn } from "@/lib/utils";

export type SwitchSize = "sm" | "md";

export interface SwitchProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "onChange" | "value" | "children"> {
  checked?: boolean;
  defaultChecked?: boolean;
  onCheckedChange?: (checked: boolean) => void;
  size?: SwitchSize;
  /** Submits `value` with a form under this name while on, like a checkbox. */
  name?: string;
  value?: string;
}

/** A toggle with role="switch". Space and Enter toggle it, as with any button. Give it a label or aria-label. */
export const Switch = forwardRef<HTMLButtonElement, SwitchProps>(function Switch(
  { checked: controlled, defaultChecked = false, onCheckedChange, size = "md", name, value = "on", disabled, className, onClick, ...props },
  ref,
) {
  const [uncontrolled, setUncontrolled] = useState(defaultChecked);
  const checked = controlled ?? uncontrolled;
  const state = checked ? "checked" : "unchecked";

  return (
    <>
      <button
        ref={ref}
        type="button"
        role="switch"
        aria-checked={checked}
        data-state={state}
        disabled={disabled}
        onClick={(event) => {
          onClick?.(event);
          if (event.defaultPrevented) return;
          if (controlled === undefined) setUncontrolled(!checked);
          onCheckedChange?.(!checked);
        }}
        className={cn(
          "relative inline-flex shrink-0 cursor-pointer items-center rounded-full p-0.5 outline-hidden",
          "transition-[background-color,box-shadow] duration-200 ease-out",
          "data-[state=checked]:bg-primary data-[state=unchecked]:bg-foreground/15 dark:data-[state=unchecked]:bg-foreground/20",
          "hover:data-[state=unchecked]:bg-foreground/20 dark:hover:data-[state=unchecked]:bg-foreground/25",
          "focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-45",
          size === "sm" ? "h-5 w-9" : "h-6 w-11",
          className,
        )}
        {...props}
      >
        <span
          aria-hidden="true"
          data-state={state}
          className={cn(
            "pointer-events-none block rounded-full shadow-[0_1px_2px_rgb(0_0_0/0.18),0_1px_1px_rgb(0_0_0/0.08)]",
            "motion-safe:transition-[translate,background-color] motion-safe:duration-200 motion-safe:ease-[cubic-bezier(.3,.8,.4,1)]",
            "data-[state=checked]:bg-primary-foreground data-[state=unchecked]:bg-background dark:data-[state=unchecked]:bg-foreground",
            size === "sm" ? "size-4 data-[state=checked]:translate-x-4" : "size-5 data-[state=checked]:translate-x-5",
          )}
        />
      </button>
      {name && checked && <input type="hidden" name={name} value={value} />}
    </>
  );
});

export interface SwitchFieldProps extends SwitchProps {
  label: ReactNode;
  description?: ReactNode;
  /** Which side the switch sits on. */
  switchPosition?: "start" | "end";
  /** Classes for the row; `className` goes to the switch. */
  containerClassName?: string;
}

/** A switch with a visible label and optional description, wired with aria-labelledby and aria-describedby. */
export function SwitchField({
  label, description, switchPosition = "end", id, containerClassName, disabled, ...switchProps
}: SwitchFieldProps) {
  const auto = useId();
  const switchId = id ?? `${auto}-switch`;
  const labelId = `${auto}-label`;
  const descriptionId = `${auto}-description`;

  return (
    <div
      data-disabled={disabled || undefined}
      className={cn(
        "group/field flex items-start gap-4",
        switchPosition === "end" ? "justify-between" : "flex-row-reverse justify-end",
        containerClassName,
      )}
    >
      <div className="flex min-w-0 flex-col gap-0.5">
        <label
          id={labelId}
          htmlFor={switchId}
          className="w-fit cursor-pointer text-sm font-medium leading-6 text-foreground group-data-[disabled]/field:cursor-not-allowed group-data-[disabled]/field:opacity-60"
        >
          {label}
        </label>
        {description && (
          <p id={descriptionId} className="text-[13px] leading-5 text-muted-foreground group-data-[disabled]/field:opacity-80">
            {description}
          </p>
        )}
      </div>
      <Switch
        id={switchId}
        aria-labelledby={labelId}
        aria-describedby={description ? descriptionId : undefined}
        disabled={disabled}
        {...switchProps}
      />
    </div>
  );
}