Skip to content
Shaken UI
Sign in

Toggle Group

Save

A segmented control for one or several choices, with a raised pill that springs to the pressed item.

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

Preview

Toggle Group preview

Installation

npx @shakenui/cli add toggle-group

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

npx @shakenui/cli add toggle-group --dry-run

Usage

toggle-group-example.tsx
import { ToggleGroup, ToggleGroupItem } from "@/components/shaken/ui/toggle-group";

function ListIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
      <path d="M5.5 4h8M5.5 8h8M5.5 12h8M2.5 4h.01M2.5 8h.01M2.5 12h.01" />
    </svg>
  );
}

function GridIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5">
      <rect x="2.5" y="2.5" width="4.5" height="4.5" rx="1" />
      <rect x="9" y="2.5" width="4.5" height="4.5" rx="1" />
      <rect x="2.5" y="9" width="4.5" height="4.5" rx="1" />
      <rect x="9" y="9" width="4.5" height="4.5" rx="1" />
    </svg>
  );
}

function GraphIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
      <circle cx="3.75" cy="8" r="1.75" />
      <circle cx="12.25" cy="3.75" r="1.75" />
      <circle cx="12.25" cy="12.25" r="1.75" />
      <path d="M5.4 7.2l5.2-2.6M5.4 8.8l5.2 2.6" />
    </svg>
  );
}

export default function ToggleGroupExample() {
  return (
    <div className="grid justify-items-start gap-6">
      <ToggleGroup aria-label="Time range" defaultValue={["24h"]}>
        <ToggleGroupItem value="1h">1h</ToggleGroupItem>
        <ToggleGroupItem value="24h">24h</ToggleGroupItem>
        <ToggleGroupItem value="7d">7 days</ToggleGroupItem>
        <ToggleGroupItem value="30d">30 days</ToggleGroupItem>
      </ToggleGroup>

      <ToggleGroup aria-label="Layout" defaultValue={["list"]}>
        <ToggleGroupItem value="list" iconOnly aria-label="List">
          <ListIcon />
        </ToggleGroupItem>
        <ToggleGroupItem value="grid" iconOnly aria-label="Grid">
          <GridIcon />
        </ToggleGroupItem>
        <ToggleGroupItem value="graph" iconOnly aria-label="Graph">
          <GraphIcon />
        </ToggleGroupItem>
      </ToggleGroup>

      <ToggleGroup aria-label="Show steps" multiple defaultValue={["running", "failed"]}>
        <ToggleGroupItem value="running">Running</ToggleGroupItem>
        <ToggleGroupItem value="failed">Failed</ToggleGroupItem>
        <ToggleGroupItem value="waiting">Waiting</ToggleGroupItem>
        <ToggleGroupItem value="done">Done</ToggleGroupItem>
      </ToggleGroup>

      <ToggleGroup variant="ghost" aria-label="Text style" multiple defaultValue={["bold"]}>
        <ToggleGroupItem value="bold" aria-label="Bold" iconOnly className="font-bold">
          B
        </ToggleGroupItem>
        <ToggleGroupItem value="italic" aria-label="Italic" iconOnly className="font-serif italic">
          I
        </ToggleGroupItem>
        <ToggleGroupItem value="code" aria-label="Code" iconOnly className="font-mono text-xs">
          {"</>"}
        </ToggleGroupItem>
      </ToggleGroup>
    </div>
  );
}

API

PropTypeDefaultDescription
value / defaultValuestring[]—The pressed items' values.
onValueChange(value: string[]) => void—Called when the pressed items change.
multiplebooleanfalseIndependent toggles instead of one choice.
variant"segmented" | "ghost""segmented"A hairline track with a sliding pill, or spaced toolbar buttons.
size"sm" | "md""md"24px or 28px items.
allowEmptybooleanfalse for single segmentedWhether the only pressed item can be released.
orientation"horizontal" | "vertical""horizontal"Layout and arrow-key direction.
iconOnlybooleanfalseToggleGroupItem: a square item for one icon; give it an aria-label.

Accessibility

  • Renders role="group" of native buttons with aria-pressed; name the group with aria-label.
  • Arrow keys move focus between items with roving tabindex; Space or Enter presses the focused item.
  • The pill springs over 350ms on click and jumps without moving when the choice changes from the keyboard.
  • Under reduced motion the pill moves without a transition.

Files

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

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

Source

The exact source the CLI installs, from /r/items/react/toggle-group/0.1.0.json.

ui/toggle-group.tsxShow
ui/toggle-group.tsx
"use client";

import { Toggle as BaseToggle } from "@base-ui/react/toggle";
import { ToggleGroup as BaseToggleGroup } from "@base-ui/react/toggle-group";
import {
  createContext,
  type KeyboardEvent,
  type PointerEvent,
  useContext,
  useLayoutEffect,
  useRef,
  useState,
} 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);
}

// A critically damped spring (bounce 0) settling in about 350ms, sampled for CSS linear().
const spring =
  "ease-[linear(0,0.044,0.144,0.263,0.384,0.495,0.593,0.675,0.744,0.8,0.844,0.88,0.908,0.929,0.946,0.959,0.969,0.977,0.982,0.987,1)]";

export type ToggleGroupVariant = "segmented" | "ghost";

const sizes = {
  sm: { text: "h-6 px-2 text-xs", icon: "size-6" },
  md: { text: "h-7 px-2.5 text-sm", icon: "size-7" },
} as const;

export type ToggleGroupSize = keyof typeof sizes;

interface GroupContextValue {
  variant: ToggleGroupVariant;
  size: ToggleGroupSize;
  pill: boolean;
}

const GroupContext = createContext<GroupContextValue>({ variant: "segmented", size: "md", pill: false });

export interface ToggleGroupProps<Value extends string = string> extends BaseToggleGroup.Props<Value> {
  /**
   * `segmented` sits the items in a hairline track; with one choice, a raised pill slides to the
   * pressed item. `ghost` spaces the items apart, like toolbar buttons.
   */
  variant?: ToggleGroupVariant;
  size?: ToggleGroupSize;
  /**
   * Whether pressing the only pressed item can clear the selection. Off for single-choice
   * segmented groups, which always keep one item pressed; on otherwise.
   */
  allowEmpty?: boolean;
}

/**
 * A row of toggle buttons sharing one value: an array of the pressed items' `value`s. Single
 * choice by default; add `multiple` for independent toggles. Arrow keys move focus between
 * items and Space or Enter presses one. The sliding pill springs over 350ms on click and
 * jumps without moving when the choice changes from the keyboard.
 */
export function ToggleGroup<Value extends string = string>({
  variant = "segmented",
  size = "md",
  multiple = false,
  allowEmpty,
  value,
  defaultValue,
  onValueChange,
  orientation = "horizontal",
  className,
  children,
  onPointerDown,
  onKeyDown,
  ...props
}: ToggleGroupProps<Value>) {
  const [uncontrolled, setUncontrolled] = useState<readonly Value[]>(defaultValue ?? []);
  const current = value ?? uncontrolled;
  const keepOne = !multiple && !(allowEmpty ?? variant === "ghost");
  const pill = variant === "segmented" && !multiple;

  const rootRef = useRef<HTMLDivElement>(null);
  const pillRef = useRef<HTMLSpanElement>(null);
  const [input, setInput] = useState<"pointer" | "keyboard">("pointer");
  const [placed, setPlaced] = useState(false);

  // Measures the pressed item and moves the pill onto it with transforms (no layout animation).
  useLayoutEffect(() => {
    const root = rootRef.current;
    const indicator = pillRef.current;
    if (!pill || !root || !indicator) return;
    const place = () => {
      const pressed = root.querySelector<HTMLElement>(":scope > [data-pressed]");
      if (!pressed) {
        indicator.style.opacity = "0";
        return;
      }
      const vertical = orientation === "vertical";
      indicator.style.opacity = "1";
      indicator.style.width = `${pressed.offsetWidth}px`;
      indicator.style.height = `${pressed.offsetHeight}px`;
      indicator.style.translate = vertical ? `0 ${pressed.offsetTop}px` : `${pressed.offsetLeft}px 0`;
      setPlaced(true);
    };
    place();
    const observer = new ResizeObserver(place);
    observer.observe(root);
    return () => observer.disconnect();
  }, [pill, current, orientation]);

  return (
    <GroupContext.Provider value={{ variant, size, pill: pill && placed }}>
      <BaseToggleGroup<Value>
        ref={rootRef}
        multiple={multiple}
        value={current}
        orientation={orientation}
        onValueChange={(next, details) => {
          if (keepOne && next.length === 0) return;
          if (value === undefined) setUncontrolled(next);
          onValueChange?.(next, details);
        }}
        data-variant={variant}
        data-input={input}
        onPointerDown={(event: PointerEvent<HTMLDivElement>) => {
          setInput("pointer");
          onPointerDown?.(event as never);
        }}
        onKeyDown={(event: KeyboardEvent<HTMLDivElement>) => {
          setInput("keyboard");
          onKeyDown?.(event as never);
        }}
        className={withBase(
          cx(
            "group/toggles relative isolate inline-flex w-fit data-[orientation=vertical]:flex-col",
            variant === "segmented"
              ? "gap-0.5 rounded-lg border border-zinc-950/10 bg-zinc-950/[0.03] p-0.5 dark:border-white/10 dark:bg-transparent"
              : "gap-1",
            "data-[disabled]:opacity-45",
          ),
          className,
        )}
        {...props}
      >
        {pill ? (
          <span
            ref={pillRef}
            aria-hidden="true"
            className={cx(
              "pointer-events-none absolute top-0 left-0 -z-10 rounded-md opacity-0",
              "bg-white shadow-[0_1px_2px_rgb(0_0_0/0.08),0_0_0_1px_rgb(0_0_0/0.06)]",
              "dark:bg-white/[0.12] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.08),0_0_0_1px_rgb(255_255_255/0.06)]",
              placed &&
                cx(
                  "group-data-[input=pointer]/toggles:transition-[translate,width,height] group-data-[input=pointer]/toggles:duration-350",
                  spring,
                  "motion-reduce:transition-none group-data-[input=pointer]/toggles:motion-reduce:transition-none",
                ),
            )}
          />
        ) : null}
        {children}
      </BaseToggleGroup>
    </GroupContext.Provider>
  );
}

export interface ToggleGroupItemProps<Value extends string = string> extends BaseToggle.Props<Value> {
  /** Identifies the item in the group's value. */
  value: Value;
  /** A square item for a single icon. Give it an `aria-label`. */
  iconOnly?: boolean;
}

/** One item in a ToggleGroup. It sets `aria-pressed`, so its state is announced. */
export function ToggleGroupItem<Value extends string = string>({ iconOnly = false, className, ...props }: ToggleGroupItemProps<Value>) {
  const { variant, size, pill } = useContext(GroupContext);
  return (
    <BaseToggle<Value>
      className={withBase(
        cx(
          "relative inline-flex shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-md font-medium whitespace-nowrap select-none",
          iconOnly ? sizes[size].icon : sizes[size].text,
          "text-zinc-500 hover:text-zinc-950 data-[pressed]:text-zinc-950",
          "dark:text-zinc-400 dark:hover:text-white dark:data-[pressed]:text-white",
          variant === "ghost"
            ? "hover:bg-zinc-950/[0.04] data-[pressed]:bg-zinc-950/[0.07] dark:hover:bg-white/[0.06] dark:data-[pressed]:bg-white/[0.1]"
            : pill
              ? ""
              : cx(
                  // Multiple choice, or before the pill is measured: each pressed item carries its own raised fill.
                  "data-[pressed]:bg-white data-[pressed]:shadow-[0_1px_2px_rgb(0_0_0/0.08),0_0_0_1px_rgb(0_0_0/0.06)]",
                  "dark:data-[pressed]:bg-white/[0.12] dark:data-[pressed]:shadow-[inset_0_1px_0_rgb(255_255_255/0.08),0_0_0_1px_rgb(255_255_255/0.06)]",
                ),
          "transition-[background-color,color,box-shadow,scale] duration-150 ease-out active:duration-100",
          "motion-safe:active:scale-[0.97] motion-reduce:transition-none",
          "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
          "data-[disabled]:pointer-events-none data-[disabled]:opacity-45",
          "[&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
        ),
        className,
      )}
      {...props}
    />
  );
}