ReactMedium

Tabs component

A tabs component shows one panel at a time with a row of tab buttons. Store the active tab (controlled or uncontrolled), render buttons with role="tab" inside a role="tablist", connect each tab to its panel with aria-controls and aria-labelledby, mark the active one with aria-selected, and support arrow-key navigation with roving tabIndex, following the WAI-ARIA Tabs pattern.

Requirements

  1. Data-driven or compound API (<Tabs><Tab/><Panel/></Tabs>).
  2. Active state with an optional defaultValue and onChange.
  3. Keyboard: Left and Right arrows move between tabs, Home and End jump to the first and last; only the active tab is in the Tab order (tabIndex={0}, others -1).
  4. ARIA roles and relationships; IDs generated with useId.
  5. Inactive panels hidden (hidden attribute or not rendered).

Design choices to discuss

  • Unmount vs hide inactive panels: unmounting saves work but loses state; React 19.2's <Activity mode="hidden"> keeps state while hidden and pauses effects.
  • Sync with the URL (?tab=billing) so tabs are linkable.
  • Lazy-load heavy panels.
  • Automatic vs manual activation: activate on focus (arrow keys) or require Enter/Space.

Libraries

Radix Tabs, React Aria Tabs, Headless UI Tab.

Code example

tsx
1import { Activity, useId, useRef, useState } from "react";
2
3type TabItem = { id: string; label: string; content: React.ReactNode };
4
5export function Tabs({ items, defaultId }: { items: TabItem[]; defaultId?: string }) {
6 const [active, setActive] = useState(defaultId ?? items[0].id);
7 const baseId = useId();
8 const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);
9
10 function onKeyDown(e: React.KeyboardEvent, index: number) {
11 const last = items.length - 1;
12 const next = e.key === "ArrowRight" ? (index === last ? 0 : index + 1)
13 : e.key === "ArrowLeft" ? (index === 0 ? last : index - 1)
14 : e.key === "Home" ? 0 : e.key === "End" ? last : null;
15 if (next === null) return;
16 e.preventDefault();
17 setActive(items[next].id);
18 tabRefs.current[next]?.focus();
19 }
20
21 return (
22 <div>
23 <div role="tablist" aria-label="Settings">
24 {items.map((t, i) => (
25 <button key={t.id} ref={(el) => { tabRefs.current[i] = el; }} role="tab" id={`${baseId}-tab-${t.id}`}
26 aria-selected={active === t.id} aria-controls={`${baseId}-panel-${t.id}`} tabIndex={active === t.id ? 0 : -1}
27 onClick={() => setActive(t.id)} onKeyDown={(e) => onKeyDown(e, i)}>
28 {t.label}
29 </button>
30 ))}
31 </div>
32 {items.map((t) => (
33 <Activity key={t.id} mode={active === t.id ? "visible" : "hidden"}> {/* keeps panel state when switching */}
34 <div role="tabpanel" id={`${baseId}-panel-${t.id}`} aria-labelledby={`${baseId}-tab-${t.id}`} tabIndex={0}>{t.content}</div>
35 </Activity>
36 ))}
37 </div>
38 );
39}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app