Segmented control
A compact switch between two to five views of the same thing: a time range, a unit, a chart type. One option is always selected and the change applies at once. For more than five options, or options that need explaining, use a select or radio buttons.
Install
npx shadcn@latest add https://thrumui.dev/r/segmented-control.jsonAdds components/ui/segmented-control.tsx and installs motion. Nothing else in your project changes.
import { SegmentedControl } from "@/components/ui/segmented-control";Data shape
type SegmentedControlOption = {
value: string; // reported by onValueChange
label: string; // text on the segment
disabled?: boolean; // shown, cannot be picked
};[
{ value: "day", label: "Day" },
{ value: "week", label: "Week" },
{ value: "month", label: "Month", disabled: true },
]Props
| Prop | Type | Default | Description |
|---|---|---|---|
options | readonly SegmentedControlOption[] | Required | The choices, in order. Values must be unique. |
value | string | – | The selected value, when the parent holds it. Use it with onValueChange. |
defaultValue | string | – | The value selected at first, when the control holds the selection itself. |
onValueChange | (value: string) => void | – | Called with the new value when the selection changes. It is not called when the selected option is picked again. |
label | string | Required | What is being chosen. It is the name of the group for screen readers. |
size | "sm" | "md" | Default "md" | sm is 30 pixels tall with 12 pixel text, md is 34 pixels tall with 14 pixel text. |
sound | boolean | Default true | Play a soft click when the selection changes, if the visitor has sound on. |
className | string | – | Sets the width. By default the control is as wide as its labels. With w-full the segments share the width. |
Motion and sound
Motion
- The thumb slides to the selected segment on a stiff spring (stiffness 1400, damping 67) and settles in about 150 ms with under 1% overshoot.
- A second change during a slide retargets the thumb from where it is.
- The thumb also follows when the control is resized or a label changes length.
- Segments keep their width when selected: each label is laid out in both weights.
- Reduced motion: the thumb moves instantly.
Sound
- A soft click with a short tone when the selection changes. Picking the selected option again is silent.
Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works
Accessibility
- It follows the WAI-ARIA radio group pattern: the control is a radiogroup named by the label, each segment is a radio with aria-checked.
- Selection is shown three ways: the filled thumb, heavier text and a different text colour.
- Disabled options are real disabled buttons: they take no focus and are announced as unavailable.
- Long labels wrap inside their segment and the control grows taller. Nothing is cut off at 240 pixels wide. When a segment is narrower than one word, the word breaks, so keep labels short where space is tight.
- The arrow keys do not swap direction in right-to-left layouts in this version.
| Keys | Action |
|---|---|
| Tab | Focus the selected option, or the first one that can be picked when none is selected. The control is one tab stop. |
| ← → ↑ ↓ | Move to the previous or next option and select it. Disabled options are skipped, and the ends wrap round. |
| Home / End | Select the first or last option that can be picked. |
| Space | Select the focused option, if it is not selected yet. |
Source
"use client";
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import { motion } from "motion/react";
import { cn } from "@/lib/utils";
import { INSTANT, SPRING, useReducedMotion } from "@/lib/thrum-motion";
import { play } from "@/lib/thrum-sound";
export type SegmentedControlOption = {
/** What `onValueChange` reports. Unique within the control. */
value: string;
/** The text on the segment. */
label: string;
/** Shown, but it cannot be picked and the arrow keys skip it. */
disabled?: boolean;
};
export type SegmentedControlProps = {
/** The choices, in order. Two to five short labels read best. */
options: readonly SegmentedControlOption[];
/** The selected value, when the parent holds it. Use with `onValueChange`. */
value?: string;
/** The value selected at first, when the control holds it itself. */
defaultValue?: string;
/** Called with the new value when the selection changes. */
onValueChange?: (value: string) => void;
/** What is being chosen. Read by screen readers. Example: "Time range". */
label: string;
/** `sm` is 30 pixels tall, `md` is 34. Longer labels wrap and the control grows taller. */
size?: "sm" | "md";
/** Play a soft click when the selection changes, if the visitor has sound on. */
sound?: boolean;
/** Size it with classes. The default is as wide as its labels; `w-full` shares the width between the segments. */
className?: string;
};
/** How far each edge of the selected segment is from the same edge of the control, in pixels. */
type Inset = { top: number; right: number; bottom: number; left: number };
/**
* A row of options where exactly one is selected. A thumb slides to the selected segment.
* It is a radio group: Tab reaches the selected option and the arrow keys change it.
*/
export function SegmentedControl({ options, value, defaultValue, onValueChange, label, size = "md", sound = true, className }: SegmentedControlProps) {
const root = useRef<HTMLDivElement>(null);
const reduced = useReducedMotion();
const [inner, setInner] = useState(defaultValue);
const selected = value ?? inner;
// Where the thumb belongs. Unknown until the segments have been measured in the browser.
const [thumb, setThumb] = useState<Inset | null>(null);
// Measure the selected segment whenever the selection, the options or any size changes.
// An observer reports once when it starts, which covers the first two; the control never reads sizes while rendering.
const optionKey = options.map((option) => option.value).join("\n");
useEffect(() => {
const group = root.current;
if (!group) return;
const observer = new ResizeObserver(() => {
const on = group.querySelector<HTMLElement>('[aria-checked="true"]');
// Measured from inside the control's border, in fractions of a pixel: label widths are rarely whole numbers.
const box = group.getBoundingClientRect();
const segment = on?.getBoundingClientRect();
// Inside a scaled parent, such as a dialog that zooms in as it opens, the rectangles are scaled and the layout is not.
const scale = Math.abs(box.width - group.offsetWidth) < 1 ? 1 : box.width / group.offsetWidth;
setThumb(
on && segment
? {
top: (segment.top - box.top) / scale - group.clientTop,
right: (box.right - segment.right) / scale - group.clientLeft,
bottom: (box.bottom - segment.bottom) / scale - group.clientTop,
left: (segment.left - box.left) / scale - group.clientLeft,
}
: null,
);
});
observer.observe(group);
for (const radio of group.querySelectorAll('[role="radio"]')) observer.observe(radio);
return () => observer.disconnect();
}, [selected, optionKey]);
const select = (next: string) => {
if (next === selected) return;
setInner(next);
onValueChange?.(next);
if (sound) play("select");
};
// One tab stop: the selected option, or the first one that can be picked when nothing is selected.
const enabled = options.filter((option) => !option.disabled);
const tabStop = enabled.some((option) => option.value === selected) ? selected : enabled[0]?.value;
const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {
const radios = Array.from(root.current?.querySelectorAll<HTMLButtonElement>('[role="radio"]:not(:disabled)') ?? []);
const at = radios.indexOf(event.currentTarget);
const target: Record<string, number> = { ArrowRight: at + 1, ArrowDown: at + 1, ArrowLeft: at - 1, ArrowUp: at - 1, Home: 0, End: radios.length - 1 };
if (!(event.key in target) || radios.length === 0) return;
event.preventDefault();
// Past either end the arrows wrap round, as in any radio group.
const next = radios[(target[event.key] + radios.length) % radios.length];
next.focus();
if (next.dataset.value !== undefined) select(next.dataset.value);
};
return (
<div
ref={root}
data-slot="segmented-control"
data-surface="control"
role="radiogroup"
aria-label={label}
className={cn("relative inline-flex max-w-full rounded-md border border-input bg-muted p-0.5", className)}
>
{thumb && (
// The thumb is a box of its own behind the labels, out of the layout, so moving it moves nothing else.
// It covers the selected segment only, with the segment's own corners: a contrast checker then reads every other label against the track.
<motion.span
aria-hidden="true"
className="pointer-events-none absolute rounded-sm bg-primary"
initial={false}
animate={{ top: thumb.top, right: thumb.right, bottom: thumb.bottom, left: thumb.left }}
transition={reduced ? INSTANT : SPRING.control}
/>
)}
{options.map((option) => {
const on = option.value === selected;
return (
<button
key={option.value}
type="button"
role="radio"
aria-checked={on}
disabled={option.disabled}
tabIndex={option.value === tabStop ? 0 : -1}
data-value={option.value}
onClick={() => select(option.value)}
onKeyDown={onKeyDown}
className={cn(
"relative grid min-w-0 flex-auto place-items-center rounded-sm text-center [overflow-wrap:anywhere] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50",
size === "sm" ? "min-h-6 px-2 py-0.5 text-xs" : "min-h-7 px-2.5 py-1 text-sm",
on ? "text-primary-foreground" : "text-muted-foreground enabled:hover:text-foreground",
// Before the first measurement there is no thumb yet, so the segment carries the fill itself.
on && !thumb && "bg-primary",
)}
>
{/* The label is laid out in both weights and one is shown, so selecting never changes a segment's width. */}
<span className={cn("col-start-1 row-start-1 font-semibold", !on && "invisible")}>{option.label}</span>
<span className={cn("col-start-1 row-start-1", on && "invisible")}>{option.label}</span>
</button>
);
})}
</div>
);
}Files and dependencies
- Adds
components/ui/segmented-control.tsx- Packages
motion- Brings along
- Motion tokensSound engine
Changelog
- 1.0.1 · 2026-12-03Corners follow the project's --radius, down to square.
- 1.0.0 · 2026-12-02First release.