Components · Navigation
note:Copy source: not an npm package.
AccessibleTabs
WAI-ARIA tabs with roving focus, arrow/Home/End keys, disabled tabs and optional manual activation.
- aria
- keyboard
- roving tabindex
- Dependencies
- None beyond React
- Source
- src/components/collection/accessible-tabs/accessible-tabs.tsx
Preview & code
A browser-based code notebook that keeps the reason next to each snippet.
React, Vite, Tailwind CSS and Ace Editor. Notes persist in localStorage.
No accounts or sync yet. Collections can’t be renamed from the UI.
Try it with the keyboard: Tab into the tabs, then use ←/→, Home and End. With manual activation, arrows move focus and Enter or Space selects.
"use client";/** * AccessibleTabs — a WAI-ARIA tabs pattern with roving focus. * * - role="tablist" / "tab" / "tabpanel" with aria-selected, aria-controls and * aria-labelledby wired automatically. * - Left/Right arrows move between tabs (wrapping), Home/End jump to the ends, * disabled tabs are skipped. * - activation="automatic" selects on arrow focus; "manual" waits for * Enter/Space, which suits panels that are expensive to render. * - Uncontrolled (defaultValue) or controlled (value + onValueChange). * - Inactive panels stay mounted but hidden, so their state survives switching. * * Styling uses Tailwind utilities backed by CSS variables (--border, --text, * --text-muted, --accent). Adjust to your design system. * * Source: Sayed Risat's portfolio component collection. Copy freely. */import { useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";export type TabItem = { /** Stable value used for selection. */ id: string; label: ReactNode; content: ReactNode; disabled?: boolean;};export type AccessibleTabsProps = { items: TabItem[]; /** Accessible name for the tab list, e.g. "Component views". */ label: string; /** Controlled selected id. */ value?: string; /** Initial selected id when uncontrolled. Defaults to the first enabled tab. */ defaultValue?: string; onValueChange?: (id: string) => void; activation?: "automatic" | "manual"; className?: string; /** Extra classes for each panel. */ panelClassName?: string;};export function AccessibleTabs({ items, label, value, defaultValue, onValueChange, activation = "automatic", className, panelClassName,}: AccessibleTabsProps) { const baseId = useId(); const firstEnabled = items.find((item) => !item.disabled)?.id; const [internal, setInternal] = useState(defaultValue ?? firstEnabled); const selected = value ?? internal; const tabRefs = useRef<Array<HTMLButtonElement | null>>([]); const tabId = (id: string) => `${baseId}-tab-${id}`; const panelId = (id: string) => `${baseId}-panel-${id}`; function select(id: string) { if (value === undefined) setInternal(id); if (id !== selected) onValueChange?.(id); } function onKeyDown(event: KeyboardEvent<HTMLButtonElement>, index: number) { const enabled = items.map((item, i) => (item.disabled ? -1 : i)).filter((i) => i >= 0); const position = enabled.indexOf(index); let target: number | undefined; switch (event.key) { case "ArrowRight": target = enabled[(position + 1) % enabled.length]; break; case "ArrowLeft": target = enabled[(position - 1 + enabled.length) % enabled.length]; break; case "Home": target = enabled[0]; break; case "End": target = enabled[enabled.length - 1]; break; default: return; } event.preventDefault(); tabRefs.current[target]?.focus(); if (activation === "automatic") select(items[target].id); } return ( <div className={className}> <div role="tablist" aria-label={label} aria-orientation="horizontal" className="flex gap-1 overflow-x-auto border-b border-[var(--border,#dce3df)]"> {items.map((item, index) => { const isSelected = item.id === selected; return ( <button key={item.id} ref={(node) => { tabRefs.current[index] = node; }} id={tabId(item.id)} type="button" role="tab" aria-selected={isSelected} aria-controls={panelId(item.id)} tabIndex={isSelected ? 0 : -1} disabled={item.disabled} onClick={() => select(item.id)} onKeyDown={(event) => onKeyDown(event, index)} className={[ "relative -mb-px inline-flex h-11 shrink-0 items-center gap-2 border-b-2 px-3.5 text-[0.9375rem] font-medium transition-colors", "focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-[var(--focus,#0b8177)] disabled:cursor-not-allowed disabled:opacity-50", isSelected ? "border-[var(--accent,#0f766e)] text-[var(--text,#1b2428)]" : "border-transparent text-[var(--text-muted,#59666a)] hover:text-[var(--text,#1b2428)]", ].join(" ")} > {item.label} </button> ); })} </div> {items.map((item) => ( <div key={item.id} id={panelId(item.id)} role="tabpanel" aria-labelledby={tabId(item.id)} hidden={item.id !== selected} tabIndex={0} className={["pt-5 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-[var(--focus,#0b8177)]", panelClassName] .filter(Boolean) .join(" ")} > {item.content} </div> ))} </div> );}When to use it
Switching between related views (preview and code, overview and details) without leaving the page, while behaving the way keyboard and screen-reader users expect tabs to behave.
Usage
- Copy
src/components/collection/accessible-tabs/accessible-tabs.tsxinto your project (from the Code tab above). - Import it from where you placed it. In this repo that’s
@/components/collection/accessible-tabs/accessible-tabs.
import { AccessibleTabs } from "@/components/collection/accessible-tabs/accessible-tabs";export function ProjectTabs() { return ( <AccessibleTabs label="Project details" items={[ { id: "overview", label: "Overview", content: <p>What it does.</p> }, { id: "stack", label: "Stack", content: <p>React, Vite, Tailwind CSS.</p> }, ]} /> );}API
| Prop | Type | Default | Description |
|---|---|---|---|
| items* (required) | TabItem[] | — | Tabs as { id, label, content, disabled? }. Ids must be unique. |
| label* (required) | string | — | Accessible name for the tab list. |
| value | string | — | Selected id when controlled. |
| defaultValue | string | first enabled tab | Initial selection when uncontrolled. |
| onValueChange | (id: string) => void | — | Called when the selection changes. |
| activation | "automatic" | "manual" | "automatic" | Select on arrow focus, or wait for Enter/Space. |
| className | string | — | Classes on the wrapper. |
| panelClassName | string | — | Classes on every panel. |
* required
Accessibility
- Tab
- Moves focus into the tab list (selected tab), then into the active panel.
- ← / →
- Moves to the previous/next enabled tab, wrapping at the ends.
- Home / End
- Moves to the first/last enabled tab.
- Enter / Space
- Selects the focused tab (needed with manual activation).
- Uses role="tablist", "tab" and "tabpanel" with aria-selected, aria-controls and aria-labelledby wired by generated ids.
- Only the selected tab is in the Tab order (roving tabindex); panels are focusable so their content is reachable.
- Disabled tabs are skipped by arrow keys and exposed as disabled.
- Inactive panels use the hidden attribute, so they are removed from the accessibility tree but keep their state.
Limits & tests
Limitations
- Horizontal orientation only.
- All panels are mounted; for very heavy panels, render content lazily inside the panel yourself.
- No overflow menu: many tabs scroll horizontally.
Tests
tests/e2e/components.spec.ts
- Arrow, Home and End keys move focus and selection with correct ARIA state
- Manual activation moves focus without selecting until Enter
- Disabled tabs are skipped
- Used for the Preview/Code switch on every component page