Skip to content
Atoms

Switch

A switch whose thumb stretches while pressed.

Primitive

Variants

3 more takes on the switch, each a single file you install on its own by its id.

aui-058Settings rows

Each switch saves itself.

$ pnpm dlx asta-ui@latest add switch-aui-058

Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/switch-aui-058.json

aui-059Icon thumb

A thumb with an icon that changes.

$ pnpm dlx asta-ui@latest add switch-aui-059

Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/switch-aui-059.json

aui-060Theme

Sun rolls into moon and re-themes the card.

$ pnpm dlx asta-ui@latest add switch-aui-060

Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/switch-aui-060.json

Installation

Primitive
  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/, installs radix-ui@base-ui/react and the colour tokens go into your CSS. This is the Radix build. Drop --radix for Base UI.This is the Base UI build, the default. Want Radix? Add --radix.

    $ pnpm dlx asta-ui@latest add switch --radix

    Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/base/switch.json

  2. Or install the package

    Don’t want the file? Import from asta-uiasta-ui/base and update with pnpm update asta-ui. Add the stylesheet once. More.

    $ pnpm add asta-ui radix-ui @base-ui/react
    import { Switch } from "asta-ui";
    import { Switch } from "asta-ui/base";
  3. Or copy it by hand

    Install radix-ui@base-ui/react, then copy this file. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import { Switch as Sw } from "radix-ui";
    import { useId, useState, type ReactNode } from "react";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    export type SwitchSize = "sm" | "md" | "lg";
    
    // Track width / height and thumb size, in px.
    const DIM: Record<SwitchSize, { w: number; h: number; t: number }> = {
      sm: { w: 30, h: 18, t: 14 },
      md: { w: 40, h: 24, t: 20 },
      lg: { w: 52, h: 30, t: 26 },
    };
    
    export interface SwitchProps {
      checked?: boolean;
      defaultChecked?: boolean;
      onCheckedChange?: (checked: boolean) => void;
      size?: SwitchSize;
      disabled?: boolean;
      label?: ReactNode;
      description?: ReactNode;
      id?: string;
      /** Form field name. */
      name?: string;
      "aria-label"?: string;
      className?: string;
    }
    
    /**
     * An on/off switch on Radix Switch (ARIA, Space/Enter, native form value through `name`). While pressed the
     * thumb stretches toward where it's about to go.
     */
    export function Switch({ checked, defaultChecked = false, onCheckedChange, size = "md", disabled, label, description, id, name, className, "aria-label": ariaLabel }: SwitchProps) {
      const auto = useId();
      const sid = id ?? auto;
      const [inner, setInner] = useState(defaultChecked);
      const [press, setPress] = useState(false);
      const on = checked ?? inner;
      const { w, h, t } = DIM[size];
      const pad = (h - t) / 2;
      const stretch = press ? t * 0.3 : 0;
      const x = on ? w - pad * 2 - t - stretch : 0;
    
      const control = (
        <Sw.Root
          id={sid}
          name={name}
          checked={on}
          onCheckedChange={(v) => {
            if (checked === undefined) setInner(v);
            onCheckedChange?.(v);
          }}
          aria-label={ariaLabel}
          aria-describedby={description ? `${sid}-d` : undefined}
          disabled={disabled}
          onPointerDown={() => setPress(true)}
          onPointerUp={() => setPress(false)}
          onPointerLeave={() => setPress(false)}
          onKeyDown={(e) => (e.key === " " || e.key === "Enter") && setPress(true)}
          onKeyUp={() => setPress(false)}
          onBlur={() => setPress(false)}
          className={cx(
            "relative shrink-0 rounded-full outline-none transition-[background-color,box-shadow] duration-300",
            "focus-visible:ring-2 focus-visible:ring-brand/50 focus-visible:ring-offset-2 focus-visible:ring-offset-paper disabled:opacity-45",
            on ? "bg-brand shadow-[inset_0_1px_2px_rgb(0_0_0/0.15)]" : "bg-[color-mix(in_srgb,var(--color-ink)_14%,var(--color-paper))] shadow-[inset_0_1px_2px_rgb(0_0_0/0.08)]",
          )}
          style={{ width: w, height: h, padding: pad }}
        >
          <Sw.Thumb
            // perf-ok: the thumb stretches a few px on press, a tiny element that only moves on interaction.
            className="block rounded-full bg-white shadow-[0_1px_2px_rgb(0_0_0/0.2),0_2px_6px_-1px_rgb(0_0_0/0.18)] transition-[transform,width] duration-[450ms] ease-[cubic-bezier(.34,1.56,.64,1)] motion-reduce:transition-none"
            style={{ width: t + stretch, height: t, transform: `translateX(${x}px)` }}
          />
        </Sw.Root>
      );
    
      if (!label) return <span className={className}>{control}</span>;
      return (
        <div className={cx("flex items-center justify-between gap-4", disabled && "opacity-60", className)}>
          <span className="min-w-0">
            <label htmlFor={sid} className={cx("block select-none text-[14px] leading-5 text-ink", !disabled && "cursor-pointer")}>
              {label}
            </label>
            {description && (
              <span id={`${sid}-d`} className="mt-0.5 block text-[13px] leading-snug text-mute">
                {description}
              </span>
            )}
          </span>
          {control}
        </div>
      );
    }
    
    export default Switch;
    
    "use client";
    
    import { Switch as Sw } from "@base-ui/react/switch";
    import { useId, useState, type ReactNode } from "react";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    export type SwitchSize = "sm" | "md" | "lg";
    
    // Track width / height and thumb size, in px.
    const DIM: Record<SwitchSize, { w: number; h: number; t: number }> = {
      sm: { w: 30, h: 18, t: 14 },
      md: { w: 40, h: 24, t: 20 },
      lg: { w: 52, h: 30, t: 26 },
    };
    
    export interface SwitchProps {
      checked?: boolean;
      defaultChecked?: boolean;
      onCheckedChange?: (checked: boolean) => void;
      size?: SwitchSize;
      disabled?: boolean;
      label?: ReactNode;
      description?: ReactNode;
      id?: string;
      /** Form field name. */
      name?: string;
      "aria-label"?: string;
      className?: string;
    }
    
    /**
     * An on/off switch on Base UI Switch (ARIA, Space/Enter, native form value through `name`). While pressed the
     * thumb stretches toward where it's about to go.
     */
    export function Switch({ checked, defaultChecked = false, onCheckedChange, size = "md", disabled, label, description, id, name, className, "aria-label": ariaLabel }: SwitchProps) {
      const auto = useId();
      const sid = id ?? auto;
      const [inner, setInner] = useState(defaultChecked);
      const [press, setPress] = useState(false);
      const on = checked ?? inner;
      const { w, h, t } = DIM[size];
      const pad = (h - t) / 2;
      const stretch = press ? t * 0.3 : 0;
      const x = on ? w - pad * 2 - t - stretch : 0;
    
      const control = (
        <Sw.Root
          id={sid}
          name={name}
          checked={on}
          onCheckedChange={(v) => {
            if (checked === undefined) setInner(v);
            onCheckedChange?.(v);
          }}
          aria-label={ariaLabel}
          aria-describedby={description ? `${sid}-d` : undefined}
          disabled={disabled}
          onPointerDown={() => setPress(true)}
          onPointerUp={() => setPress(false)}
          onPointerLeave={() => setPress(false)}
          onKeyDown={(e) => (e.key === " " || e.key === "Enter") && setPress(true)}
          onKeyUp={() => setPress(false)}
          onBlur={() => setPress(false)}
          className={cx(
            "relative shrink-0 rounded-full outline-none transition-[background-color,box-shadow] duration-300",
            "focus-visible:ring-2 focus-visible:ring-brand/50 focus-visible:ring-offset-2 focus-visible:ring-offset-paper disabled:opacity-45",
            on ? "bg-brand shadow-[inset_0_1px_2px_rgb(0_0_0/0.15)]" : "bg-[color-mix(in_srgb,var(--color-ink)_14%,var(--color-paper))] shadow-[inset_0_1px_2px_rgb(0_0_0/0.08)]",
          )}
          style={{ width: w, height: h, padding: pad }}
        >
          <Sw.Thumb
            // perf-ok: the thumb stretches a few px on press, a tiny element that only moves on interaction.
            className="block rounded-full bg-white shadow-[0_1px_2px_rgb(0_0_0/0.2),0_2px_6px_-1px_rgb(0_0_0/0.18)] transition-[transform,width] duration-[450ms] ease-[cubic-bezier(.34,1.56,.64,1)] motion-reduce:transition-none"
            style={{ width: t + stretch, height: t, transform: `translateX(${x}px)` }}
          />
        </Sw.Root>
      );
    
      if (!label) return <span className={className}>{control}</span>;
      return (
        <div className={cx("flex items-center justify-between gap-4", disabled && "opacity-60", className)}>
          <span className="min-w-0">
            <label htmlFor={sid} className={cx("block select-none text-[14px] leading-5 text-ink", !disabled && "cursor-pointer")}>
              {label}
            </label>
            {description && (
              <span id={`${sid}-d`} className="mt-0.5 block text-[13px] leading-snug text-mute">
                {description}
              </span>
            )}
          </span>
          {control}
        </div>
      );
    }
    
    export default Switch;
    
  4. Or ask your AI agent

    Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.

    Add the Astabyte UI Switch component to my project.
    
    A switch whose thumb stretches while pressed.
    It includes: sm, md, lg, label.
    
    Install it (Radix build):
    ```sh
    pnpm dlx asta-ui@latest add switch --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/switch.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { Switch } from "@/components/astabyte/switch";
    ```
    
    Usage example and props: https://ui.astabyte.com/switch
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Radix primitives from the radix-ui package).
    - Stay on Radix: install other Astabyte UI components with `--radix` so the project uses one primitive library.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
    Add the Astabyte UI Switch component to my project.
    
    A switch whose thumb stretches while pressed.
    It includes: sm, md, lg, label.
    
    Install it (Base UI build):
    ```sh
    pnpm dlx asta-ui@latest add switch
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/base/switch.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { Switch } from "@/components/astabyte/switch";
    ```
    
    Usage example and props: https://ui.astabyte.com/switch
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Base UI primitives from the @base-ui/react package).
    - Stay on Base UI: install other Astabyte UI components without `--radix` so the project uses one primitive library.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
  5. Or use plain HTML + CSS

    Not on React? Use it from Django, Rails, Laravel, Go html/template, htmx or a static page. Load asta.css and asta.js once (the head.html tab), then paste the markup. The ui.astabyte.com/cdn link is temporary: pin a version from jsDelivr for production. More in HTML + CSS.

    <div style="display:grid;gap:16px;max-width:360px">
      <label class="asta-switch">
        <span><span class="asta-switch-label">Deploy alerts</span><span class="asta-switch-desc">Push when an Astabyte build fails.</span></span>
        <span class="asta-switch-track"><input type="checkbox" role="switch" class="asta-switch-input" name="alerts" checked><span class="asta-switch-thumb" aria-hidden="true"></span></span>
      </label>
      <label class="asta-switch asta-switch-sm">
        <span><span class="asta-switch-label">Weekly digest</span></span>
        <span class="asta-switch-track"><input type="checkbox" role="switch" class="asta-switch-input" name="digest"><span class="asta-switch-thumb" aria-hidden="true"></span></span>
      </label>
    </div>

Usage

The demo above, as code.

"use client";

import { useState } from "react";
import { Switch } from "@/components/astabyte/switch";

export default function SwitchDemo() {
  const [dark, setDark] = useState(false);

  return (
    <div className="flex min-h-[420px] w-full items-center justify-center p-6 sm:p-10">
      <div className="flex w-full max-w-sm flex-col gap-6">
        <div className="flex flex-col gap-1 rounded-xl bg-paper p-2 shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_10%,transparent)]">
          <Switch className="rounded-[10px] px-3 py-3 hover:bg-paper-2" label="Push notifications" description="Mentions and replies only." defaultChecked />
          <Switch className="rounded-[10px] px-3 py-3 hover:bg-paper-2" label="Weekly digest" description="A summary every Monday." />
          <Switch
            className="rounded-[10px] px-3 py-3 hover:bg-paper-2"
            label="Dark mode"
            description={dark ? "Easy on the eyes." : "Bright and clear."}
            checked={dark}
            onCheckedChange={setDark}
          />
        </div>
        <div className="flex items-center justify-center gap-6">
          <Switch size="sm" defaultChecked aria-label="Small" />
          <Switch size="md" defaultChecked aria-label="Medium" />
          <Switch size="lg" defaultChecked aria-label="Large" />
          <Switch size="md" disabled aria-label="Disabled" />
        </div>
      </div>
    </div>
  );
}