Component
Segmented Button
A joined single-choice control that behaves like a radiogroup: one selected option at a time. Use for 2–5 mutually exclusive options in compact toolbars.
- Component
- React
- TSX
- Tailwind CSS
- MIT
Preview
Live component
9:41 100%
devsnips.dev/library/react/components/buttons/segmented-button/ fluid · no fixed width 100%
Install
Add to your project
npx devsnips add React/Components/Buttons/segmented-button React/Components/Buttons/segmented-button import { useRef } from "react";
import type { HTMLAttributes, ReactNode, KeyboardEvent } from "react";
/* DevSnips React — SegmentedButton
* Joined single-choice control (radiogroup semantics). One selected option
* at a time. ArrowLeft/Right rove selection and focus.
*/
export type ButtonSize = "xs" | "sm" | "md" | "lg" | "xl";
export interface SegmentedOption {
value: string;
label: ReactNode;
icon?: string;
disabled?: boolean;
}
export interface SegmentedButtonProps extends HTMLAttributes<HTMLDivElement> {
options: SegmentedOption[];
value: string;
onChange: (value: 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 SegmentedButton({
options,
value,
onChange,
size = "sm",
label,
className,
...rest
}: SegmentedButtonProps) {
const refs = useRef<Array<HTMLButtonElement | null>>([]);
const height = SIZES[size];
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();
const opt = options[next];
if (!opt.disabled) {
onChange(opt.value);
refs.current[next]?.focus();
}
}
}
return (
<div role="radiogroup" 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 selected = opt.value === value;
return (
<button
key={opt.value}
ref={(el) => { refs.current[i] = el; }}
type="button"
role="radio"
aria-checked={selected}
disabled={opt.disabled}
onClick={() => onChange(opt.value)}
onKeyDown={(e) => onKey(e, i)}
className={cx(
SEG_BASE,
height,
"rounded-none",
i > 0 && "-ml-px border-l border-[var(--ds-color-border)]",
selected ? "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 SegmentedButton; /* 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 } 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 SegmentedButton({
options,
value,
onChange,
size = "sm",
label,
className,
...rest
}) {
const refs = useRef([]);
const height = SIZES[size];
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();
const opt = options[next];
if (!opt.disabled) {
onChange(opt.value);
refs.current[next]?.focus();
}
}
}
return <div role="radiogroup" 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 selected = opt.value === value;
return <button
key={opt.value}
ref={(el) => {
refs.current[i] = el;
}}
type="button"
role="radio"
aria-checked={selected}
disabled={opt.disabled}
onClick={() => onChange(opt.value)}
onKeyDown={(e) => onKey(e, i)}
className={cx(
SEG_BASE,
height,
"rounded-none",
i > 0 && "-ml-px border-l border-[var(--ds-color-border)]",
selected ? "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 SegmentedButton; # Segmented Button
A joined single-choice control that behaves like a radiogroup: one selected option at a time. Use for 2–5 mutually exclusive options in compact toolbars.
## 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
<SegmentedButton label="View" value={view} onChange={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 }>` | — |
| `value` | `string` | — (controlled) |
| `onChange` | `(value: string) => void` | — |
| `size` | `ButtonSize` | `sm` |
| `label` | `string` | — (radiogroup `aria-label`) |
Plus all native `HTMLAttributes<HTMLDivElement>`.
## Variants
Single segmented style: bordered container, selected segment uses `surface-active` + `aria-checked="true"` (radiogroup semantics).
## 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 · selected (`aria-checked`, surface-active + font-weight) · disabled (via `disabled` on individual options).
## Accessibility
Renders `role="radiogroup"` with `aria-label`. Each segment is a `role="radio"` button with `aria-checked`. **Keyboard**: ArrowLeft/Right move between segments and select (roving selection, like a native radiogroup). Each segment has a focus-visible ring.
## 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 multi-select, use ToggleGroup. SegmentedButton is strictly single-choice. Keep to 2–5 options; for more, use a Select. 102 lines UTF-8 · LF · Spaces: 2
Continue browsing