Component
Toggle Group
A joined set of toggles. `type="single"` behaves like a radiogroup (one on); `type="multiple"` like a group of checkboxes. Selected segments use `surface-active` + `aria-pressed`, with arrow-key roving.
- Component
- React
- TSX
- Tailwind CSS
- MIT
Preview
Live component
9:41 100%
devsnips.dev/library/react/components/buttons/toggle-group/ fluid · no fixed width 100%
Install
Add to your project
npx devsnips add React/Components/Buttons/toggle-group React/Components/Buttons/toggle-group import { useRef, useState } from "react";
import type { HTMLAttributes, ReactNode, KeyboardEvent } from "react";
/* DevSnips React — ToggleGroup
* Joined toggles, single or multi select. Selected segments use
* surface-active + aria-pressed. Arrow keys rove focus.
*/
export type ButtonSize = "xs" | "sm" | "md" | "lg" | "xl";
export type ToggleGroupType = "single" | "multiple";
export interface ToggleOption {
value: string;
label: ReactNode;
icon?: string;
disabled?: boolean;
}
export interface ToggleGroupProps extends HTMLAttributes<HTMLDivElement> {
options: ToggleOption[];
type?: ToggleGroupType;
value?: string | string[];
defaultValue?: string | string[];
onValueChange?: (value: string | null | string[]) => void;
size?: ButtonSize;
label?: string;
}
function cx(...parts: Array<string | false | null | undefined>): string {
return parts.filter(Boolean).join(" ");
}
const SIZES: Record<ButtonSize, string> = {
xs: "h-7 gap-1 px-2 text-xs [&_svg]:size-[14px]",
sm: "h-8 gap-1.5 px-3 text-xs [&_svg]:size-[14px]",
md: "h-9 gap-2 px-3.5 text-[13px] [&_svg]:size-4",
lg: "h-10 gap-2 px-4 text-[13px] [&_svg]:size-[18px]",
xl: "h-11 gap-2 px-5 text-sm [&_svg]:size-5",
};
const SEG_BASE =
"inline-flex items-center justify-center gap-2 border-0 bg-transparent px-3 font-medium leading-none " +
"transition-colors duration-150 ease-out motion-reduce:transition-none " +
"focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-[var(--ds-color-focus-ring)] " +
"disabled:pointer-events-none disabled:opacity-50";
export function ToggleGroup({
options,
type = "single",
value,
defaultValue,
onValueChange,
size = "sm",
label,
className,
...rest
}: ToggleGroupProps) {
const initialArr = defaultValue
? (Array.isArray(defaultValue) ? defaultValue : [defaultValue])
: [];
const [internal, setInternal] = useState<string[]>(initialArr);
const isControlled = value !== undefined;
const ctrlArr = Array.isArray(value) ? value : value ? [value] : [];
const current = isControlled ? ctrlArr : internal;
const refs = useRef<Array<HTMLButtonElement | null>>([]);
function isActive(v: string) { return current.indexOf(v) !== -1; }
function toggle(v: string) {
let next: string[];
if (type === "single") next = isActive(v) ? [] : [v];
else next = isActive(v) ? current.filter((x) => x !== v) : [...current, v];
if (!isControlled) setInternal(next);
onValueChange?.(type === "single" ? next[0] ?? null : next);
}
function onKey(e: KeyboardEvent<HTMLButtonElement>, i: number) {
const n = options.length;
let next = -1;
if (e.key === "ArrowRight" || e.key === "ArrowDown") next = (i + 1) % n;
else if (e.key === "ArrowLeft" || e.key === "ArrowUp") next = (i - 1 + n) % n;
if (next >= 0) { e.preventDefault(); refs.current[next]?.focus(); }
}
return (
<div role="group" aria-label={label} className={cx("inline-flex overflow-hidden rounded-[var(--ds-radius-sm)] border border-[var(--ds-color-border-strong)]", className)} {...rest}>
{options.map((opt, i) => {
const on = isActive(opt.value);
return (
<button
key={opt.value}
ref={(el) => { refs.current[i] = el; }}
type="button"
aria-pressed={on}
disabled={opt.disabled}
onClick={() => toggle(opt.value)}
onKeyDown={(e) => onKey(e, i)}
className={cx(
SEG_BASE,
SIZES[size],
"rounded-none",
i > 0 && "-ml-px border-l border-[var(--ds-color-border)]",
on ? "bg-[var(--ds-color-surface-active)] font-semibold" : "hover:bg-[var(--ds-color-surface-hover)]",
)}
>
{opt.icon ? <Icon name={opt.icon} className="shrink-0" /> : null}
<span>{opt.label}</span>
</button>
);
})}
</div>
);
}
export default ToggleGroup; /* DevSnips React — JavaScript parity build.
* Same API, behavior, and classes as code.tsx; TypeScript types removed.
* Regenerated from code.tsx — edit code.tsx and re-run the generator.
*/
import { useRef, useState } from "react";
function cx(...parts) {
return parts.filter(Boolean).join(" ");
}
const SIZES = {
xs: "h-7 gap-1 px-2 text-xs [&_svg]:size-[14px]",
sm: "h-8 gap-1.5 px-3 text-xs [&_svg]:size-[14px]",
md: "h-9 gap-2 px-3.5 text-[13px] [&_svg]:size-4",
lg: "h-10 gap-2 px-4 text-[13px] [&_svg]:size-[18px]",
xl: "h-11 gap-2 px-5 text-sm [&_svg]:size-5"
};
const SEG_BASE = "inline-flex items-center justify-center gap-2 border-0 bg-transparent px-3 font-medium leading-none transition-colors duration-150 ease-out motion-reduce:transition-none focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-[var(--ds-color-focus-ring)] disabled:pointer-events-none disabled:opacity-50";
export function ToggleGroup({
options,
type = "single",
value,
defaultValue,
onValueChange,
size = "sm",
label,
className,
...rest
}) {
const initialArr = defaultValue ? Array.isArray(defaultValue) ? defaultValue : [defaultValue] : [];
const [internal, setInternal] = useState(initialArr);
const isControlled = value !== undefined;
const ctrlArr = Array.isArray(value) ? value : value ? [value] : [];
const current = isControlled ? ctrlArr : internal;
const refs = useRef([]);
function isActive(v) {
return current.indexOf(v) !== -1;
}
function toggle(v) {
let next;
if (type === "single") next = isActive(v) ? [] : [v];
else next = isActive(v) ? current.filter((x) => x !== v) : [...current, v];
if (!isControlled) setInternal(next);
onValueChange?.(type === "single" ? next[0] ?? null : next);
}
function onKey(e, i) {
const n = options.length;
let next = -1;
if (e.key === "ArrowRight" || e.key === "ArrowDown") next = (i + 1) % n;
else if (e.key === "ArrowLeft" || e.key === "ArrowUp") next = (i - 1 + n) % n;
if (next >= 0) {
e.preventDefault();
refs.current[next]?.focus();
}
}
return <div role="group" aria-label={label} className={cx("inline-flex overflow-hidden rounded-[var(--ds-radius-sm)] border border-[var(--ds-color-border-strong)]", className)} {...rest}>
{options.map((opt, i) => {
const on = isActive(opt.value);
return <button
key={opt.value}
ref={(el) => {
refs.current[i] = el;
}}
type="button"
aria-pressed={on}
disabled={opt.disabled}
onClick={() => toggle(opt.value)}
onKeyDown={(e) => onKey(e, i)}
className={cx(
SEG_BASE,
SIZES[size],
"rounded-none",
i > 0 && "-ml-px border-l border-[var(--ds-color-border)]",
on ? "bg-[var(--ds-color-surface-active)] font-semibold" : "hover:bg-[var(--ds-color-surface-hover)]"
)}
>
{opt.icon ? <Icon name={opt.icon} className="shrink-0" /> : null}
<span>{opt.label}</span>
</button>;
})}
</div>;
}
export default ToggleGroup; # Toggle Group
A joined set of toggles. `type="single"` behaves like a radiogroup (one on); `type="multiple"` like a group of checkboxes. Selected segments use `surface-active` + `aria-pressed`, with arrow-key roving.
## Installation
This component requires **React** and **Tailwind CSS**. Drop `code.tsx` (or `code.jsx` for JavaScript projects) into your project. Tailwind utility classes are included directly in the component, so no separate CSS file is required.
The component consumes the DevSnips semantic design tokens through Tailwind arbitrary values (for example `bg-[var(--ds-color-primary)]`). Define the `--ds-*` tokens once in your theme — see [React/DESIGN_TOKENS.md](../../../DESIGN_TOKENS.md) for the full token spec.
## Usage
```tsx
<ToggleGroup type="single" value={view} onValueChange={setView} options={[{value:"list",label:"List"},{value:"grid",label:"Grid"}}] />
```
## JavaScript
A `code.jsx` build is provided for projects that ship plain JSX. It exposes the same API and behavior as `code.tsx` — only the TypeScript types are removed.
## Props
| Prop | Type | Default |
|---|---|---|
| `options` | `Array<{ value: string; label: ReactNode; icon?: string; disabled?: boolean }>` | — |
| `type` | `single \| multiple` | `single` |
| `value` | `string` (single) \| `string[]` (multiple) | — (controlled) |
| `defaultValue` | same shape as `value` | — (uncontrolled initial) |
| `onValueChange` | `(value: string \| null) \| (string[]) => void` | — |
| `size` | `ButtonSize` | `sm` |
| `label` | `string` | — (group `aria-label`) |
Plus all native `HTMLAttributes<HTMLDivElement>`.
## Variants
Single bordered container. Selected segments use `surface-active` + `aria-pressed="true"`. Unselected are transparent; hover lifts to `surface-hover`.
## Sizes
xs (28px) · sm (32px) · **md (36px, default)** · lg (40px) · xl (44px). Horizontal padding scales 8 → 20px; icons scale 14 → 20px. Default is `sm` for compact toolbars.
## States
default · hover · focus-visible · pressed (`aria-pressed`, surface-active + font-weight) · disabled (per option).
## Accessibility
Renders `role="group"` with `aria-label`. Each segment is a native `<button>` with `aria-pressed`. **Keyboard**: ArrowLeft/Right move focus (roving); Space/Enter toggles. Single-select toggles behave like a radiogroup but expose `aria-pressed` (one true at a time).
## Styling
Tailwind classes are included directly in the component and consume the DevSnips semantic design tokens (`--ds-*`) via arbitrary values. The button themes with the surface automatically in light and dark mode. No component-specific CSS file is needed.
## Design Tokens
See [React/DESIGN_TOKENS.md](../../../DESIGN_TOKENS.md) for the authoritative token specification. This button uses the semantic color, radius, and motion tokens; define them once in your project theme and every button in the family stays in sync.
## Notes
For strictly single-choice radiogroup semantics, prefer SegmentedButton. ToggleGroup is for flexible single- or multi-select toggle sets. 113 lines UTF-8 · LF · Spaces: 2
Continue browsing