Icon Button Group
Accessible icon button toolbar with toggles, tooltips, shortcuts and roving focus, for editors and tools.
- Buttons
- Productivity / Docs
- React only · 0 deps
- 1 file
Browser support · All evergreen browsers. Tooltip pairing uses :has() with a graceful fallback.
Install. One command, or copy the file.
$
npx shadcn@latest add https://freedesignmd.com/r/icon-button-group.json- Byte-identical to the preview
- No Tailwind or config needed
- SSR-safe · keyboard accessible
- Respects reduced motion & transparency
components/buttons/icon-button-group.tsx
1/**2 * IconButtonGroup, a toolbar of icon buttons with tooltips, toggle3 * (aria-pressed) states, exclusive sub-groups and separators.4 *5 * Props: groups: ToolItem[][], each inner array is a visual group with a6 * separator between groups. ToolItem = { id, label, icon, shortcut?,7 * kind?: "toggle" | "action", exclusive?: string, disabled? }.8 * pressed (Record<id, boolean>) + onToggle(id, next) for toggles,9 * onAction(id) for actions, size ("sm" | "md"), aria-label, theme.10 * Items sharing the same `exclusive` key behave like a radio set.11 *12 * Browser support: all evergreen browsers.13 * Accessibility: role="toolbar" with a roving tabindex (ArrowLeft/Right,14 * Home/End); toggles expose aria-pressed; every button has an aria-label and15 * aria-keyshortcuts; tooltips (role="tooltip") appear on hover after 400ms16 * (instantly once warm) and on keyboard focus, and close on Escape.17 * Reduced motion: tooltip fades only.18 */19import { useEffect, useId, useRef, useState } from "react";20import type { KeyboardEvent, ReactNode } from "react";21 22export interface ToolItem {23 id: string;24 label: string;25 icon: ReactNode;26 shortcut?: string;27 kind?: "toggle" | "action";28 exclusive?: string;29 disabled?: boolean;30}31 32export interface IconButtonGroupProps {33 groups: ToolItem[][];34 pressed?: Record<string, boolean>;35 onToggle?: (id: string, next: boolean) => void;36 onAction?: (id: string) => void;37 size?: "sm" | "md";38 theme?: "light" | "dark";39 className?: string;40 "aria-label"?: string;41}42 43export function IconButtonGroup({44 groups,45 pressed = {},46 onToggle,47 onAction,48 size = "md",49 theme,50 className,51 "aria-label": ariaLabel = "Formatting",52}: IconButtonGroupProps) {53 const uid = useId();54 const bar = useRef<HTMLDivElement>(null);55 const flat = groups.flat();56 const [active, setActive] = useState(flat[0]?.id);57 const [tip, setTip] = useState<{ id: string; x: number; y: number } | null>(null);58 const timer = useRef(0);59 const warm = useRef(0);60 61 useEffect(() => () => window.clearTimeout(timer.current), []);62 63 const showTip = (id: string, el: HTMLElement, delay: number) => {64 window.clearTimeout(timer.current);65 const go = () => setTip({ id, x: el.offsetLeft + el.offsetWidth / 2, y: el.offsetTop });66 if (delay <= 0 || Date.now() - warm.current < 600) go();67 else timer.current = window.setTimeout(go, delay);68 };69 const hideTip = () => {70 window.clearTimeout(timer.current);71 setTip((t) => {72 if (t) warm.current = Date.now();73 return null;74 });75 };76 77 const onKey = (e: KeyboardEvent) => {78 if (e.key === "Escape") return hideTip();79 const btns = Array.from(bar.current?.querySelectorAll<HTMLButtonElement>("button:not(:disabled)") ?? []);80 const i = btns.indexOf(document.activeElement as HTMLButtonElement);81 let n = -1;82 if (e.key === "ArrowRight") n = (i + 1) % btns.length;83 else if (e.key === "ArrowLeft") n = (i - 1 + btns.length) % btns.length;84 else if (e.key === "Home") n = 0;85 else if (e.key === "End") n = btns.length - 1;86 if (n >= 0) {87 e.preventDefault();88 btns[n].focus();89 }90 };91 92 const press = (it: ToolItem) => {93 if (it.kind === "action") return onAction?.(it.id);94 onToggle?.(it.id, !pressed[it.id]);95 };96 97 const tipItem = tip ? flat.find((f) => f.id === tip.id) : null;98 99 return (100 <div className={`fd-ibg${className ? " " + className : ""}`} data-size={size} data-fd-theme={theme}>101 <style>{css}</style>102 <div ref={bar} className="fd-ibg-bar" role="toolbar" aria-label={ariaLabel} onKeyDown={onKey}>103 {groups.map((g, gi) => (104 <div key={gi} className="fd-ibg-group" role="group">105 {g.map((it) => {106 const isToggle = it.kind !== "action";107 return (108 <button109 key={it.id}110 type="button"111 className="fd-ibg-btn"112 aria-label={it.label}113 aria-pressed={isToggle ? !!pressed[it.id] : undefined}114 aria-keyshortcuts={it.shortcut}115 aria-describedby={tip?.id === it.id ? `${uid}-tip` : undefined}116 disabled={it.disabled}117 tabIndex={active === it.id ? 0 : -1}118 onClick={() => {119 press(it);120 setActive(it.id);121 }}122 onFocus={(e) => {123 setActive(it.id);124 if (e.currentTarget.matches(":focus-visible")) showTip(it.id, e.currentTarget, 0);125 }}126 onBlur={hideTip}127 onPointerEnter={(e) => e.pointerType === "mouse" && showTip(it.id, e.currentTarget, 400)}128 onPointerLeave={hideTip}129 onPointerDown={hideTip}130 >131 <span className="fd-ibg-ic">{it.icon}</span>132 </button>133 );134 })}135 {gi < groups.length - 1 && <span className="fd-ibg-sep" aria-hidden="true" />}136 </div>137 ))}138 {tip && tipItem && (139 <div id={`${uid}-tip`} role="tooltip" className="fd-ibg-tip" style={{ left: tip.x, top: tip.y }}>140 {tipItem.label}141 {tipItem.shortcut && <kbd>{tipItem.shortcut}</kbd>}142 </div>143 )}144 </div>145 </div>146 );147}148 149const css = `150:where(.fd-ibg,.fd-ibg *){box-sizing:border-box;margin:0;padding:0;font:inherit;letter-spacing:inherit;color:inherit;text-decoration:none;list-style:none}151:where(.fd-ibg,.fd-ibg *)::before,:where(.fd-ibg,.fd-ibg *)::after{box-sizing:border-box}152:where(.fd-ibg svg){display:block;flex-shrink:0}153:where(.fd-ibg button){appearance:none;-webkit-appearance:none;background:none;border:0;border-radius:0}154.fd-ibg{155 --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;156 --i-bg:#fff;--i-fg:#0B0B0F;--i-mut:#5F5F6B;--i-hover:rgba(11,11,15,.06);--i-on:rgba(0,122,255,.12);--i-on-fg:#0058C7;--i-line:rgba(11,11,15,.1);--i-ring:rgba(0,122,255,.7);157 --i-tip-bg:#0B0B0F;--i-tip-fg:#F5F5F7;158 --i-sh:0 0 0 1px var(--i-line),0 1px 2px rgba(11,11,15,.05),0 8px 24px -12px rgba(11,11,15,.22);159 display:inline-block;max-width:100%;160 font:500 12px/1 ui-sans-serif,-apple-system,BlinkMacSystemFont,"SF Pro Text","Inter","Segoe UI",Roboto,sans-serif;color:var(--i-fg);161}162[data-fd-theme="dark"] .fd-ibg,.fd-ibg[data-fd-theme="dark"]{--i-bg:#1C1C22;--i-fg:#F5F5F7;--i-mut:#A1A1AD;--i-hover:rgba(255,255,255,.08);--i-on:rgba(10,132,255,.24);--i-on-fg:#6CB4FF;--i-line:rgba(255,255,255,.1);--i-ring:rgba(10,132,255,.85);--i-tip-bg:#F5F5F7;--i-tip-fg:#0B0B0F;163 --i-sh:0 0 0 1px var(--i-line),0 1px 0 rgba(255,255,255,.05) inset,0 8px 24px -12px rgba(0,0,0,.7)}164.fd-ibg[data-size="sm"]{--i-b:28px;--i-ic:16px}165.fd-ibg[data-size="md"]{--i-b:34px;--i-ic:18px}166.fd-ibg-bar{position:relative;display:inline-flex;align-items:center;gap:4px;max-width:100%;flex-wrap:wrap;padding:4px;border-radius:calc(var(--i-b)/3.4 + 8px);background:var(--i-bg);box-shadow:var(--i-sh)}167.fd-ibg-group{display:inline-flex;align-items:center;gap:2px}168.fd-ibg-sep{width:1px;height:18px;margin:0 4px 0 6px;background:var(--i-line)}169.fd-ibg-btn{position:relative;display:grid;place-items:center;width:var(--i-b);height:var(--i-b);border-radius:calc(var(--i-b)/3.4 + 4px);170 appearance:none;-webkit-appearance:none;border:0;outline:0;cursor:pointer;-webkit-tap-highlight-color:transparent;background:transparent;color:var(--i-mut);171 transform:scale(1);transition:transform 420ms var(--fd-spring),background-color var(--fd-dur-1) var(--fd-ease-out),color var(--fd-dur-1) var(--fd-ease-out)}172.fd-ibg-ic{display:grid;place-items:center;width:var(--i-ic);height:var(--i-ic)}.fd-ibg-ic svg{width:100%;height:100%}173@media (hover:hover){.fd-ibg-btn:hover:not(:disabled){background:var(--i-hover);color:var(--i-fg)}}174.fd-ibg-btn[aria-pressed="true"]{background:var(--i-on);color:var(--i-on-fg)}175.fd-ibg-btn:active:not(:disabled){transform:scale(.92);transition:transform var(--fd-dur-1) var(--fd-ease-out)}176.fd-ibg-btn:focus-visible{outline:2px solid var(--i-ring);outline-offset:1px}177.fd-ibg-btn:disabled{opacity:.35;cursor:not-allowed}178.fd-ibg-tip{position:absolute;z-index:10;transform:translate(-50%,calc(-100% - 10px));display:flex;align-items:center;gap:8px;padding:6px 8px 6px 10px;border-radius:8px;background:var(--i-tip-bg);color:var(--i-tip-fg);white-space:nowrap;pointer-events:none;179 font:500 12px/1 inherit;font-family:inherit;box-shadow:0 4px 12px rgba(0,0,0,.25);animation:fd-ibg-tip var(--fd-dur-2) var(--fd-ease-out)}180.fd-ibg-tip:not(:has(kbd)){padding-right:10px}181.fd-ibg-tip kbd{font:500 11px/1 ui-monospace,"SF Mono","JetBrains Mono",Menlo,monospace;padding:3px 5px;border-radius:5px;background:rgba(127,127,140,.28);color:inherit;opacity:.85}182.fd-ibg-tip::after{content:"";position:absolute;left:50%;top:100%;width:8px;height:8px;margin:-4px 0 0 -4px;background:var(--i-tip-bg);transform:rotate(45deg);border-radius:0 0 2px 0}183@keyframes fd-ibg-tip{from{opacity:0;transform:translate(-50%,calc(-100% - 6px)) scale(.96)}}184@media (prefers-reduced-motion:reduce){.fd-ibg-btn,.fd-ibg-btn:active:not(:disabled){transition:background-color 1ms;transform:none}.fd-ibg-tip{animation:fd-ibg-fade 100ms linear}}185@keyframes fd-ibg-fade{from{opacity:0}}186@media (prefers-contrast:more){.fd-ibg-btn[aria-pressed="true"]{box-shadow:0 0 0 1px currentColor}}187`;188 189/* ───────────────────────────── demo ───────────────────────────── */190 191const S = ({ children }: { children: ReactNode }) => (192 <svg aria-hidden="true" focusable="false" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">{children}</svg>193);194const icons = {195 bold: <S><path d="M7 5h6a3.5 3.5 0 0 1 0 7H7zM7 12h7a3.5 3.5 0 0 1 0 7H7z" /></S>,196 italic: <S><path d="M19 4h-9M14 20H5M15 4L9 20" /></S>,197 underline: <S><path d="M7 4v7a5 5 0 0 0 10 0V4M5 20h14" /></S>,198 link: <S><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1" /></S>,199 bullets: <S><path d="M9 6h11M9 12h11M9 18h11M4.5 6h.01M4.5 12h.01M4.5 18h.01" /></S>,200 left: <S><path d="M4 6h16M4 10h10M4 14h16M4 18h10" /></S>,201 center: <S><path d="M4 6h16M7 10h10M4 14h16M7 18h10" /></S>,202 right: <S><path d="M4 6h16M10 10h10M4 14h16M10 18h10" /></S>,203};204 205const isMac = () => typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform);206 207export function Demo() {208 const [pressed, setPressed] = useState<Record<string, boolean>>({ "align-left": true, bold: true });209 const [mod, setMod] = useState("Ctrl ");210 useEffect(() => setMod(isMac() ? "⌘ " : "Ctrl "), []);211 212 const groups: ToolItem[][] = [213 [214 { id: "bold", label: "Bold", icon: icons.bold, shortcut: `${mod}B` },215 { id: "italic", label: "Italic", icon: icons.italic, shortcut: `${mod}I` },216 { id: "underline", label: "Underline", icon: icons.underline, shortcut: `${mod}U` },217 ],218 [219 { id: "bullets", label: "Bulleted list", icon: icons.bullets },220 { id: "link", label: "Link", icon: icons.link, shortcut: `${mod}K` },221 ],222 [223 { id: "align-left", label: "Align left", icon: icons.left, exclusive: "align" },224 { id: "align-center", label: "Align center", icon: icons.center, exclusive: "align" },225 { id: "align-right", label: "Align right", icon: icons.right, exclusive: "align" },226 ],227 ];228 const flat = groups.flat();229 230 const toggle = (id: string, on: boolean) => {231 const ex = flat.find((f) => f.id === id)?.exclusive;232 const next = { ...pressed };233 if (ex) flat.filter((f) => f.exclusive === ex).forEach((f) => (next[f.id] = false));234 next[id] = ex === "align" ? true : on; // alignment always has one active235 setPressed(next);236 };237 238 return (239 <div className="fd-ibgd">240 <style>{demoCss}</style>241 <IconButtonGroup groups={groups} pressed={pressed} onToggle={toggle} aria-label="Text formatting" />242 </div>243 );244}245 246const demoCss = `247.fd-ibgd,.fd-ibgd *,.fd-ibgd *::before,.fd-ibgd *::after{box-sizing:border-box}248.fd-ibgd{display:flex;align-items:center;justify-content:center;min-height:100vh;width:100%;margin:0;padding:32px 16px;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}249`;More Buttons. Same file contract.
Questions about Icon Button Group
Run npx shadcn@latest add https://freedesignmd.com/r/icon-button-group.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.
Accessible icon button toolbar with toggles, tooltips, shortcuts and roving focus, for editors and tools. 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. Tooltip pairing uses :has() with a graceful fallback.
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.


