Skip to content
Atoms

Toggle group

Press one or many, the highlight slides.

Installation

  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/ and the colour tokens go into your CSS.

    $ pnpm dlx asta-ui@latest add toggle-group

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

  2. Or install the package

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

    $ pnpm add asta-ui
    import { ToggleGroup } from "asta-ui/toggle-group";
  3. Or copy it by hand

    Copy this file. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import { useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    export interface ToggleGroupOption {
      value: string;
      label?: ReactNode;
      icon?: ReactNode;
      disabled?: boolean;
      /** Accessible name, needed when the option is icon-only. */
      "aria-label"?: string;
    }
    
    interface ToggleGroupBase {
      options: ToggleGroupOption[];
      size?: "sm" | "md";
      /** Stretch to the parent's width, options sharing it evenly. */
      full?: boolean;
      disabled?: boolean;
      /** Accessible name for the group, e.g. "Text alignment". */
      label?: string;
      className?: string;
    }
    
    export interface ToggleGroupSingleProps extends ToggleGroupBase {
      type?: "single";
      /** The pressed option. An empty string means none. */
      value?: string;
      defaultValue?: string;
      onValueChange?: (value: string) => void;
      /** Pressing the active option again clears it. */
      allowEmpty?: boolean;
    }
    
    export interface ToggleGroupMultipleProps extends ToggleGroupBase {
      type: "multiple";
      value?: string[];
      defaultValue?: string[];
      onValueChange?: (value: string[]) => void;
    }
    
    export type ToggleGroupProps = ToggleGroupSingleProps | ToggleGroupMultipleProps;
    
    const EASE = "cubic-bezier(.16,1,.3,1)";
    
    const reduced = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    
    /**
     * A row of toggle buttons. In single mode one stays pressed and its background slides over from the last
     * one. In multiple mode each pressed button fills on its own. Arrow keys move focus (and select, in single mode),
     * Space or Enter presses.
     */
    export function ToggleGroup(props: ToggleGroupProps) {
      const { options, size = "md", full, disabled, label, className } = props;
      const multiple = props.type === "multiple";
    
      const [innerOne, setInnerOne] = useState(!multiple ? (props.defaultValue ?? "") : "");
      const [innerMany, setInnerMany] = useState<string[]>(multiple ? (props.defaultValue ?? []) : []);
      const one = !multiple ? (props.value ?? innerOne) : "";
      const many = multiple ? (props.value ?? innerMany) : [];
      const isOn = (v: string) => (multiple ? many.includes(v) : one === v);
    
      const root = useRef<HTMLDivElement>(null);
      const prevOne = useRef(one);
      const enabled = options.filter((o) => !o.disabled && !disabled);
    
      // Roving tab stop: the focused option, else the first pressed one, else the first enabled one.
      const [focusVal, setFocusVal] = useState<string | null>(null);
      const stop =
        (focusVal !== null && enabled.some((o) => o.value === focusVal) && focusVal) ||
        enabled.find((o) => isOn(o.value))?.value ||
        enabled[0]?.value;
    
      const press = (v: string) => {
        if (multiple) {
          const next = many.includes(v) ? many.filter((x) => x !== v) : [...many, v];
          // Keep the options' order so the value is stable whatever the click order.
          const ordered = options.map((o) => o.value).filter((x) => next.includes(x));
          if (props.value === undefined) setInnerMany(ordered);
          props.onValueChange?.(ordered);
        } else {
          const next = one === v ? (props.allowEmpty ? "" : v) : v;
          if (next === one) return;
          if (props.value === undefined) setInnerOne(next);
          props.onValueChange?.(next);
        }
      };
    
      // Single mode: FLIP the new background from the old button's box, so it slides with transform only.
      useLayoutEffect(() => {
        if (multiple) return;
        const from = prevOne.current;
        prevOne.current = one;
        if (from === one || !one || !root.current) return;
        const btns = Array.from(root.current.querySelectorAll<HTMLElement>("[data-tg-value]"));
        const next = btns.find((b) => b.dataset.tgValue === one);
        const prev = btns.find((b) => b.dataset.tgValue === from);
        const ind = next?.querySelector<HTMLElement>("[data-tg-ind]");
        if (!next || !ind || reduced()) return;
        ind.style.transition = "none";
        if (prev && prev.offsetWidth) {
          const dx = prev.offsetLeft - next.offsetLeft;
          const s = prev.offsetWidth / next.offsetWidth;
          ind.style.transform = `translateX(${dx}px) scaleX(${s})`;
        } else {
          ind.style.opacity = "0";
          ind.style.transform = "scale(.94)";
        }
        void ind.offsetWidth;
        ind.style.transition = `transform .44s ${EASE}, opacity .25s ${EASE}`;
        ind.style.transform = "";
        ind.style.opacity = "";
      }, [one, multiple]);
    
      const onKey = (e: KeyboardEvent<HTMLDivElement>) => {
        const keys = ["ArrowRight", "ArrowDown", "ArrowLeft", "ArrowUp", "Home", "End"];
        if (!keys.includes(e.key) || !enabled.length) return;
        e.preventDefault();
        const at = enabled.findIndex((o) => o.value === stop);
        let i = at;
        if (e.key === "Home") i = 0;
        else if (e.key === "End") i = enabled.length - 1;
        else if (e.key === "ArrowRight" || e.key === "ArrowDown") i = (at + 1) % enabled.length;
        else i = (at - 1 + enabled.length) % enabled.length;
        const v = enabled[i].value;
        setFocusVal(v);
        root.current?.querySelector<HTMLElement>(`[data-tg-value="${CSS.escape(v)}"]`)?.focus();
        // Single mode is a radio group: moving selects, like native radios.
        if (!multiple && v !== one) press(v);
      };
    
      const h = size === "sm" ? "h-8 text-[13px]" : "h-9 text-[13.5px]";
    
      return (
        <div
          ref={root}
          role={multiple ? "group" : "radiogroup"}
          aria-label={label}
          aria-disabled={disabled || undefined}
          onKeyDown={onKey}
          className={cx(
            "relative inline-flex gap-0.5 rounded-[10px] bg-paper-2 p-1 shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_6%,transparent)]",
            full && "flex w-full",
            disabled && "opacity-50",
            className,
          )}
        >
          {options.map((o) => {
            const on = isOn(o.value);
            const off = disabled || o.disabled;
            return (
              <button
                key={o.value}
                type="button"
                data-tg-value={o.value}
                role={multiple ? undefined : "radio"}
                aria-checked={multiple ? undefined : on}
                aria-pressed={multiple ? on : undefined}
                aria-label={o["aria-label"]}
                disabled={off}
                tabIndex={o.value === stop ? 0 : -1}
                onFocus={() => setFocusVal(o.value)}
                onClick={() => press(o.value)}
                className={cx(
                  "group/tg relative inline-flex select-none items-center justify-center gap-1.5 whitespace-nowrap rounded-[7px] font-medium tracking-[-0.01em] outline-none transition-[color,scale] duration-200 focus-visible:ring-2 focus-visible:ring-brand/50 active:scale-[0.97] disabled:pointer-events-none motion-reduce:transition-none [&_svg]:h-[1.05em] [&_svg]:w-[1.05em]",
                  h,
                  o.label ? (size === "sm" ? "px-3" : "px-3.5") : size === "sm" ? "w-8" : "w-9",
                  full && "flex-1",
                  on ? "text-ink" : "text-mute hover:text-ink",
                  o.disabled && !disabled && "opacity-40",
                )}
              >
                <span
                  aria-hidden
                  data-tg-ind
                  className={cx(
                    "pointer-events-none absolute inset-0 origin-left rounded-[7px] bg-paper shadow-[0_1px_2px_rgb(0_0_0/0.07),0_3px_10px_-4px_rgb(0_0_0/0.16),inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_8%,transparent)]",
                    // Multiple mode fades each background on its own. Single mode is driven by the FLIP above.
                    multiple && "transition-[opacity,scale] duration-300 ease-[cubic-bezier(.16,1,.3,1)] motion-reduce:transition-none",
                    on ? "scale-100 opacity-100" : multiple ? "scale-[.94] opacity-0" : "opacity-0",
                  )}
                />
                {o.icon && <span className={cx("relative flex transition-colors duration-200", on && "text-brand")}>{o.icon}</span>}
                {o.label && <span className="relative">{o.label}</span>}
              </button>
            );
          })}
        </div>
      );
    }
    
    export default ToggleGroup;
    
  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 Toggle group component to my project.
    
    Press one or many, the highlight slides.
    It includes: single, multiple, sliding background, icons, allowEmpty, full, keys.
    
    Install it:
    ```sh
    pnpm dlx asta-ui@latest add toggle-group --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/toggle-group.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 { ToggleGroup } from "@/components/astabyte/toggle-group";
    ```
    
    Usage example and props: https://ui.astabyte.com/toggle-group
    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.
    - 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.

    <form style="display:flex;flex-direction:column;align-items:flex-start;gap:16px"><div style="display:flex;flex-wrap:wrap;align-items:flex-start;gap:24px"><div role="radiogroup" data-asta-toggle="single" data-allow-empty aria-label="Text alignment" class="asta-toggle-group"><label class="asta-toggle-group-item"><input type="radio" name="align" value="left" checked aria-label="Align left" > <span aria-hidden="true" data-asta-ind class="asta-toggle-group-ind"></span> <span class="asta-toggle-group-icon" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 4h10M3 8h6M3 12h8"></path></svg></span> </label><label class="asta-toggle-group-item"><input type="radio" name="align" value="center" aria-label="Align center" > <span aria-hidden="true" data-asta-ind class="asta-toggle-group-ind"></span> <span class="asta-toggle-group-icon" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 4h10M5 8h6M4 12h8"></path></svg></span> </label><label class="asta-toggle-group-item"><input type="radio" name="align" value="right" aria-label="Align right" > <span aria-hidden="true" data-asta-ind class="asta-toggle-group-ind"></span> <span class="asta-toggle-group-icon" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 4h10M7 8h6M5 12h8"></path></svg></span> </label></div><div role="group" data-asta-toggle="multiple" aria-label="Text style" class="asta-toggle-group"><label class="asta-toggle-group-item asta-toggle-group-text"><input type="checkbox" name="style" value="bold" checked > <span aria-hidden="true" data-asta-ind class="asta-toggle-group-ind"></span> <span class="asta-toggle-group-label">Bold</span></label><label class="asta-toggle-group-item asta-toggle-group-text"><input type="checkbox" name="style" value="italic" > <span aria-hidden="true" data-asta-ind class="asta-toggle-group-ind"></span> <span class="asta-toggle-group-label">Italic</span></label><label class="asta-toggle-group-item asta-toggle-group-text"><input type="checkbox" name="style" value="underline" > <span aria-hidden="true" data-asta-ind class="asta-toggle-group-ind"></span> <span class="asta-toggle-group-label">Underline</span></label></div></div></form>

Usage

The demo above, as code.

"use client";

import { useState } from "react";
import { ToggleGroup } from "@/components/astabyte/toggle-group";

const Icon = ({ d }: { d: string }) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
    <path d={d} />
  </svg>
);

const ALIGN = [
  { value: "left", icon: <Icon d="M4 6h16M4 10h10M4 14h16M4 18h10" />, "aria-label": "Align left" },
  { value: "center", icon: <Icon d="M4 6h16M7 10h10M4 14h16M7 18h10" />, "aria-label": "Align centre" },
  { value: "right", icon: <Icon d="M4 6h16M10 10h10M4 14h16M10 18h10" />, "aria-label": "Align right" },
];

const STYLE = [
  { value: "bold", icon: <Icon d="M7 4.5h5.5a3.75 3.75 0 0 1 0 7.5H7ZM7 12h6.5a3.75 3.75 0 0 1 0 7.5H7Z" />, "aria-label": "Bold" },
  { value: "italic", icon: <Icon d="M10 4.5h8M6 19.5h8M14 4.5l-4 15" />, "aria-label": "Italic" },
  { value: "underline", icon: <Icon d="M7 4.5V11a5 5 0 0 0 10 0V4.5M5.5 20h13" />, "aria-label": "Underline" },
  { value: "strike", icon: <Icon d="M16.5 7.5c-.6-1.8-2.4-3-4.5-3-2.5 0-4.5 1.5-4.5 3.5 0 1.6 1 2.6 3 3.25M4 12h16M15.6 14.5c.6.6.9 1.3.9 2 0 2-2 3.5-4.5 3.5-2.2 0-4-1.2-4.6-3" />, "aria-label": "Strikethrough" },
];

const RANGES = [
  { value: "1d", label: "1D" },
  { value: "1w", label: "1W" },
  { value: "1m", label: "1M" },
  { value: "1y", label: "1Y" },
  { value: "all", label: "All" },
];

export default function ToggleGroupDemo() {
  const [align, setAlign] = useState("left");
  const [marks, setMarks] = useState<string[]>(["bold"]);
  const [range, setRange] = useState("1m");

  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-8">
        <div className="rounded-xl p-4 shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_10%,transparent)]">
          <div className="flex flex-wrap items-center gap-2">
            <ToggleGroup type="multiple" label="Text style" size="sm" options={STYLE} value={marks} onValueChange={setMarks} />
            <ToggleGroup label="Text alignment" size="sm" options={ALIGN} value={align} onValueChange={setAlign} />
          </div>
          <p
            className="mt-4 text-[14px] leading-relaxed text-ink-2"
            style={{
              textAlign: align as "left" | "center" | "right",
              fontWeight: marks.includes("bold") ? 600 : 400,
              fontStyle: marks.includes("italic") ? "italic" : "normal",
              textDecoration: [marks.includes("underline") && "underline", marks.includes("strike") && "line-through"].filter(Boolean).join(" ") || "none",
            }}
          >
            Good tools get out of the way. You notice the work, not the buttons.
          </p>
        </div>

        <div className="flex flex-col gap-3 px-1">
          <div className="flex items-baseline justify-between">
            <span className="text-[13px] text-mute">Portfolio</span>
            <span className="text-[13px] tabular-nums text-brand">+4.2% · {RANGES.find((r) => r.value === range)?.label}</span>
          </div>
          <ToggleGroup label="Chart range" full options={RANGES} value={range} onValueChange={setRange} />
        </div>

        <p className="text-center text-[12.5px] text-mute">Style buttons stack: arrows move, Space presses. The others pick one as you arrow through.</p>
      </div>
    </div>
  );
}