Skip to content

Segmented Control

React segmented control with a sliding thumb on a spring, badges and arrow-key selection. A radio-group toggle.

  • Buttons
  • SaaS
  • React only · 0 deps
  • 1 file
Full screen

Browser support · All evergreen browsers.

Install. One command, or copy the file.

$npx shadcn@latest add https://freedesignmd.com/r/segmented-control.json
  • Byte-identical to the preview
  • No Tailwind or config needed
  • SSR-safe · keyboard accessible
  • Respects reduced motion & transparency
components/buttons/segmented-control.tsx
1/**
2 * SegmentedControl, a single-choice control with a thumb that slides
3 * between options on a spring (billing period, view mode, density…).
4 *
5 * Props: options[] ({ value, label, badge?, icon?, disabled? }), value /
6 * defaultValue / onChange, size ("sm" | "md" | "lg"), fullWidth,
7 * aria-label (required unless aria-labelledby), theme.
8 * CSS vars: --fd-seg-accent (thumb tint), --fd-seg-radius.
9 *
10 * Browser support: all evergreen browsers; the thumb is positioned from
11 * measured offsets (ResizeObserver) so any label width works.
12 * Accessibility: role="radiogroup" with role="radio" options and a roving
13 * tabindex. ArrowLeft/Right/Up/Down move AND select (like native radios),
14 * Home/End jump. Reduced motion: the thumb jumps without overshoot.
15 */
16import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
17import type { KeyboardEvent, ReactNode } from "react";
18
19export interface SegmentOption {
20 value: string;
21 label: ReactNode;
22 badge?: ReactNode;
23 icon?: ReactNode;
24 disabled?: boolean;
25}
26
27export interface SegmentedControlProps {
28 options: SegmentOption[];
29 value?: string;
30 defaultValue?: string;
31 onChange?: (value: string) => void;
32 size?: "sm" | "md" | "lg";
33 fullWidth?: boolean;
34 theme?: "light" | "dark";
35 className?: string;
36 "aria-label"?: string;
37 "aria-labelledby"?: string;
38}
39
40export function SegmentedControl({
41 options,
42 value,
43 defaultValue,
44 onChange,
45 size = "md",
46 fullWidth,
47 theme,
48 className,
49 ...aria
50}: SegmentedControlProps) {
51 const [inner, setInner] = useState(defaultValue ?? options[0]?.value);
52 const current = value ?? inner;
53 const refs = useRef<Record<string, HTMLButtonElement | null>>({});
54 const track = useRef<HTMLDivElement>(null);
55 const [rect, setRect] = useState<{ x: number; w: number } | null>(null);
56 const [ready, setReady] = useState(false);
57
58 const measure = useCallback(() => {
59 const el = refs.current[current];
60 if (el) setRect({ x: el.offsetLeft, w: el.offsetWidth });
61 }, [current]);
62
63 useLayoutEffect(measure, [measure, options.length]);
64 useEffect(() => {
65 const t = window.setTimeout(() => setReady(true), 30);
66 const ro = typeof ResizeObserver !== "undefined" ? new ResizeObserver(measure) : null;
67 if (ro && track.current) ro.observe(track.current);
68 Object.values(refs.current).forEach((n) => n && ro?.observe(n));
69 return () => {
70 window.clearTimeout(t);
71 ro?.disconnect();
72 };
73 }, [measure]);
74
75 const select = (v: string) => {
76 if (value === undefined) setInner(v);
77 onChange?.(v);
78 };
79
80 const onKey = (e: KeyboardEvent) => {
81 const enabled = options.filter((o) => !o.disabled);
82 const i = enabled.findIndex((o) => o.value === current);
83 let n = -1;
84 if (e.key === "ArrowRight" || e.key === "ArrowDown") n = (i + 1) % enabled.length;
85 else if (e.key === "ArrowLeft" || e.key === "ArrowUp") n = (i - 1 + enabled.length) % enabled.length;
86 else if (e.key === "Home") n = 0;
87 else if (e.key === "End") n = enabled.length - 1;
88 if (n < 0) return;
89 e.preventDefault();
90 const next = enabled[n];
91 select(next.value);
92 refs.current[next.value]?.focus();
93 };
94
95 return (
96 <div className={`fd-seg${className ? " " + className : ""}`} data-size={size} data-full={fullWidth || undefined} data-ready={ready || undefined} data-fd-theme={theme}>
97 <style>{css}</style>
98 <div ref={track} className="fd-seg-track" role="radiogroup" onKeyDown={onKey} {...aria}>
99 {rect && <span className="fd-seg-thumb" aria-hidden="true" style={{ transform: `translateX(${rect.x}px)`, width: rect.w }} />}
100 {options.map((o) => {
101 const on = o.value === current;
102 return (
103 <button
104 key={o.value}
105 ref={(n) => {
106 refs.current[o.value] = n;
107 }}
108 type="button"
109 role="radio"
110 aria-checked={on}
111 tabIndex={on ? 0 : -1}
112 disabled={o.disabled}
113 className="fd-seg-opt"
114 onClick={() => select(o.value)}
115 >
116 {o.icon && <span className="fd-seg-ic">{o.icon}</span>}
117 <span className="fd-seg-label">{o.label}</span>
118 {o.badge && <span className="fd-seg-badge">{o.badge}</span>}
119 </button>
120 );
121 })}
122 </div>
123 </div>
124 );
125}
126
127const css = `
128:where(.fd-seg,.fd-seg *){box-sizing:border-box;margin:0;padding:0;font:inherit;letter-spacing:inherit;color:inherit;text-decoration:none;list-style:none}
129:where(.fd-seg,.fd-seg *)::before,:where(.fd-seg,.fd-seg *)::after{box-sizing:border-box}
130:where(.fd-seg svg){display:block;flex-shrink:0}
131:where(.fd-seg button){appearance:none;-webkit-appearance:none;background:none;border:0;border-radius:0}
132.fd-seg{
133 --fd-ease-out:cubic-bezier(.22,1,.36,1);--fd-spring:cubic-bezier(.34,1.56,.64,1);--fd-dur-1:120ms;--fd-dur-2:240ms;--fd-dur-3:420ms;
134 --g-track:rgba(11,11,15,.06);--g-thumb:#fff;--g-fg:#0B0B0F;--g-mut:#6B6B76;--g-ring:rgba(0,122,255,.7);--g-badge-bg:rgba(0,122,255,.12);--g-badge-fg:#0058C7;
135 --g-thumb-sh:0 0 0 .5px rgba(11,11,15,.06),0 1px 2px rgba(11,11,15,.12),0 3px 8px -2px rgba(11,11,15,.12);
136 display:inline-flex;vertical-align:middle;max-width:100%;
137 font:500 14px/1 ui-sans-serif,-apple-system,BlinkMacSystemFont,"SF Pro Text","Inter","Segoe UI",Roboto,sans-serif;letter-spacing:-.005em;color:var(--g-fg);
138}
139[data-fd-theme="dark"] .fd-seg,.fd-seg[data-fd-theme="dark"]{--g-track:rgba(255,255,255,.07);--g-thumb:#34343D;--g-fg:#F5F5F7;--g-mut:#9A9AA6;--g-ring:rgba(10,132,255,.85);--g-badge-bg:rgba(48,209,88,.18);--g-badge-fg:#5BE382;
140 --g-thumb-sh:0 1px 0 rgba(255,255,255,.08) inset,0 0 0 .5px rgba(0,0,0,.4),0 2px 6px rgba(0,0,0,.4)}
141.fd-seg[data-full]{display:flex;width:100%}
142.fd-seg[data-size="sm"]{--g-h:28px;--g-px:12px;--g-fs:13px}
143.fd-seg[data-size="md"]{--g-h:36px;--g-px:16px;--g-fs:14px}
144.fd-seg[data-size="lg"]{--g-h:44px;--g-px:22px;--g-fs:15px}
145.fd-seg-track{position:relative;display:inline-flex;align-items:stretch;padding:3px;border-radius:9999px;background:var(--g-track);max-width:100%;overflow-x:auto;scrollbar-width:none}
146.fd-seg-track::-webkit-scrollbar{display:none}
147.fd-seg[data-full] .fd-seg-track{display:flex;width:100%}
148.fd-seg[data-full] .fd-seg-opt{flex:1}
149.fd-seg-thumb{position:absolute;z-index:0;left:0;top:3px;bottom:3px;border-radius:9999px;background:var(--g-thumb);box-shadow:var(--g-thumb-sh);pointer-events:none;will-change:transform,width}
150.fd-seg[data-ready] .fd-seg-thumb{transition:transform var(--fd-dur-3) var(--fd-spring),width var(--fd-dur-3) var(--fd-spring)}
151.fd-seg-opt{position:relative;z-index:1;display:inline-flex;align-items:center;justify-content:center;gap:8px;height:calc(var(--g-h) - 6px);padding:0 var(--g-px);border-radius:9999px;
152 appearance:none;-webkit-appearance:none;border:0;outline:0;cursor:pointer;user-select:none;-webkit-tap-highlight-color:transparent;background:transparent;white-space:nowrap;
153 color:var(--g-mut);font-family:inherit;font-size:var(--g-fs);font-weight:500;line-height:1;letter-spacing:inherit;
154 transform:scale(1);transition:color var(--fd-dur-2) var(--fd-ease-out),transform var(--fd-dur-3) var(--fd-spring)}
155.fd-seg-opt[aria-checked="true"]{color:var(--g-fg)}
156@media (hover:hover){.fd-seg-opt[aria-checked="false"]:hover:not(:disabled){color:var(--g-fg)}}
157.fd-seg-opt:active{transform:scale(.96);transition:transform var(--fd-dur-1) var(--fd-ease-out)}
158.fd-seg-opt:focus-visible{outline:2px solid var(--g-ring);outline-offset:1px}
159.fd-seg-opt:disabled{opacity:.4;cursor:not-allowed}
160.fd-seg-ic{display:grid;place-items:center;width:16px;height:16px}.fd-seg-ic svg{width:100%;height:100%}
161.fd-seg-label{display:block}
162.fd-seg-badge{display:inline-flex;align-items:center;height:20px;padding:0 7px;border-radius:9999px;background:var(--g-badge-bg);color:var(--g-badge-fg);font-size:11px;font-weight:600;letter-spacing:0}
163@media (prefers-reduced-motion:reduce){.fd-seg[data-ready] .fd-seg-thumb{transition:transform 1ms linear,width 1ms linear}.fd-seg-opt,.fd-seg-opt:active{transition:none;transform:none}}
164@media (prefers-contrast:more){.fd-seg-track{box-shadow:0 0 0 1px currentColor}.fd-seg-thumb{box-shadow:0 0 0 1px currentColor}}
165`;
166
167/* ───────────────────────────── demo ───────────────────────────── */
168
169export function Demo() {
170 const [billing, setBilling] = useState("yearly");
171 return (
172 <div className="fd-segd">
173 <style>{demoCss}</style>
174 <SegmentedControl
175 aria-label="Billing period"
176 size="lg"
177 value={billing}
178 onChange={setBilling}
179 options={[
180 { value: "monthly", label: "Monthly" },
181 { value: "yearly", label: "Yearly", badge: "-20%" },
182 ]}
183 />
184 </div>
185 );
186}
187
188const demoCss = `
189.fd-segd,.fd-segd *,.fd-segd *::before,.fd-segd *::after{box-sizing:border-box}
190.fd-segd{display:flex;align-items:center;justify-content:center;min-height:100vh;width:100%;margin:0;padding:32px 20px;overflow:hidden;background:#f4f4f4;color:#1d1d1f;font:400 15px/1.4 ui-sans-serif,-apple-system,BlinkMacSystemFont,"SF Pro Text","Inter","Segoe UI",Roboto,sans-serif;letter-spacing:normal;-webkit-font-smoothing:antialiased}
191`;

More Buttons. Same file contract.

Button Core, buttons preview: React button component with 5 variants, 3 sizes, icon slots, a loading to success morph and a springy press

Button Core

React button component with 5 variants, 3 sizes, icon slots, a loading to success morph and a springy press.

Shimmer Button, buttons preview: Shimmer button for React: a dark capsule with a travelling light sweep and rotating border glow, built for…

Shimmer Button

Shimmer button for React: a dark capsule with a travelling light sweep and rotating border glow, built for one main CTA.

Magnetic Button, buttons preview: Magnetic button for React that leans toward your cursor on a spring, with the label drifting further than the…

Magnetic Button

Magnetic button for React that leans toward your cursor on a spring, with the label drifting further than the shell.

Questions about Segmented Control

Run npx shadcn@latest add https://freedesignmd.com/r/segmented-control.json, or open the page and copy the file into your project. It has zero dependencies besides React. What you copy is the exact file that renders the live demo.

React segmented control with a sliding thumb on a spring, badges and arrow-key selection. A radio-group toggle. It is a free, MIT-licensed React buttons component from the freedesignmd library.

Yes. It is free and MIT-licensed, use, modify and ship it in personal and commercial projects without attribution.

All evergreen browsers.

Yes. It is a plain React component with its own styles, so it runs in Next.js, Vite, Remix and Lovable projects, and it needs no Tailwind setup. It has zero dependencies besides React.