Sub topic 13
Accessibility in compound components
This chapter assumes you can build the context-based Tabs component from the earlier chapters. You should also know what aria-* attributes are and how onKeyDown works. The goal is to make the compound component usable with a keyboard and a screen reader, without taking layout control away from the consumer.
Why compound components need extra care
A compound component splits one widget into several elements that the consumer arranges. That flexibility has a cost. A screen reader can't see your component tree. It reads the final DOM, so the parts must agree on roles, ids, and focus behavior even though the consumer wrote the markup.
The shared context is where that agreement lives. Because Tabs already owns the selected value, it can also own the identifiers that tie the parts together. The consumer never has to pass an id.
The pattern to follow
The WAI-ARIA Authoring Practices describe a tabs widget with a fixed contract:
| Part | Role | Required attributes |
|---|---|---|
| Container of the tabs | `tablist` | `aria-label` or `aria-labelledby` |
| Each tab | `tab` | `aria-selected`, `aria-controls`, `id`, `tabIndex` |
| Each panel | `tabpanel` | `id`, `aria-labelledby` |
The keyboard contract has two parts:
- Only the selected tab is in the page's Tab order. Arrow keys move between tabs.
- Home and End jump to the first and last tab.
This is called a roving tabindex. The selected tab has tabIndex={0} and the others have tabIndex={-1}. Pressing Tab leaves the whole tab list in one step. A page with 12 tabs does not cost the keyboard user 12 key presses.
Generating ids in the parent
Tabs and panels reference each other by id, so both sides must derive the same string. useId produces a stable, unique string per component instance. Two Tabs on one page never collide. Server and client renders also match.
import { createContext, useContext, useId, useRef, useState } from 'react';
const TabsContext = createContext(null);
function useTabs() {
const ctx = useContext(TabsContext);
if (!ctx) {
throw new Error('Tabs subcomponents must be rendered inside <Tabs>');
}
return ctx;
}
export function Tabs({ defaultValue, children }) {
const [value, setValue] = useState(defaultValue);
const baseId = useId();
return (
<TabsContext.Provider value={{ value, setValue, baseId }}>
<div>{children}</div>
</TabsContext.Provider>
);
}
function TabList({ label, children }) {
const { setValue } = useTabs();
const listRef = useRef(null);
function handleKeyDown(event) {
const tabs = Array.from(listRef.current.querySelectorAll('[role="tab"]'));
const index = tabs.indexOf(event.target);
if (index === -1) return;
let next;
switch (event.key) {
case 'ArrowRight':
next = (index + 1) % tabs.length;
break;
case 'ArrowLeft':
next = (index - 1 + tabs.length) % tabs.length;
break;
case 'Home':
next = 0;
break;
case 'End':
next = tabs.length - 1;
break;
default:
return;
}
event.preventDefault();
tabs[next].focus();
setValue(tabs[next].dataset.value);
}
return (
<div role="tablist" aria-label={label} ref={listRef} onKeyDown={handleKeyDown}>
{children}
</div>
);
}
function Tab({ value, children }) {
const { value: active, setValue, baseId } = useTabs();
const selected = active === value;
return (
<button
type="button"
role="tab"
id={`${baseId}-tab-${value}`}
aria-selected={selected}
aria-controls={`${baseId}-panel-${value}`}
tabIndex={selected ? 0 : -1}
data-value={value}
onClick={() => setValue(value)}
>
{children}
</button>
);
}
function Panel({ value, children }) {
const { value: active, baseId } = useTabs();
const selected = active === value;
return (
<div
role="tabpanel"
id={`${baseId}-panel-${value}`}
aria-labelledby={`${baseId}-tab-${value}`}
hidden={!selected}
tabIndex={0}
>
{selected ? children : null}
</div>
);
}
Tabs.List = TabList;
Tabs.Tab = Tab;
Tabs.Panel = Panel;The consumer's code gets shorter, because the role="tablist" wrapper now lives in Tabs.List:
import { Tabs } from './Tabs';
export function Example() {
return (
<Tabs defaultValue="one">
<Tabs.List label="Account settings">
<Tabs.Tab value="one">Profile</Tabs.Tab>
<Tabs.Tab value="two">Billing</Tabs.Tab>
</Tabs.List>
<Tabs.Panel value="one">Profile form</Tabs.Panel>
<Tabs.Panel value="two">Billing form</Tabs.Panel>
</Tabs>
);
}How the keyboard flow works
When focus is on a tab and the user presses an arrow key, the event bubbles to the tablist. The handler reads the DOM to find its siblings. It does not need a registry of tabs in context. That keeps the consumer free to wrap tabs in extra elements or to render them from an array.
This version selects a tab as soon as it receives focus, which the APG calls automatic activation. It suits panels that render instantly. If switching panels is slow, use manual activation. In that case the arrow keys only move focus, and Enter or Space selects.
Decisions and gotchas
Keep `hidden` panels in the DOM
The first Tabs example returned null for inactive panels. Each tab's aria-controls then pointed at an id that did not exist. The code above keeps every panel element and uses the hidden attribute. Content renders only for the selected panel, so you keep the cost savings of lazy rendering. The ids stay valid.
Ids from `useId` are not CSS selectors
useId returns strings such as :r0:. These are valid in id and aria-* attributes. They break querySelector('#...') unless escaped. Use data-* attributes or refs for lookups, as the handler above does.
Tab values become part of the id
If a consumer passes value="my tab", the id contains a space. An id with a space is invalid HTML, and aria-controls treats it as two ids. Document that value must be a simple string with no whitespace. In development, you can also add a check that throws.
Focus the right element
tabs[next].focus() must run before or alongside the state update. If you only update state, focus stays on the old tab, and the next arrow press starts from the wrong place. Don't use useEffect to move focus after a state change when the event handler can do it directly.
Don't rely on roles alone
role="tab" on a div does not make it focusable or clickable. Use button. A native button gives you Enter and Space activation and focus styles for free.
Where this fits with other patterns
The accessible wiring lives in the compound component's context. That is a strong argument for compound components over render props or a single large component with config props, because the parts that must stay in sync are written once. If you later add control props, the ids and keyboard logic don't change. Only the source of value does.
Exercise
A teammate's Tabs renders <Tabs.Panel> as active === value ? <div role="tabpanel">...</div> : null and each Tab has aria-controls set to the panel id. What accessibility problem does this cause, and how do you fix it without rendering every panel's content?
Show answer
Inactive tabs have aria-controls pointing to an id that is not in the DOM, so the reference is broken. Always render the panel element with its id and aria-labelledby, set the hidden attribute when it is not selected, and render the children only when it is selected.
Exercise
Why does the selected tab have tabIndex={0} while the others have tabIndex={-1}, and what does the user gain?
Show answer
This is a roving tabindex. Only the selected tab is in the page's Tab order, so one Tab press moves focus past the entire tab list. Arrow keys then move between tabs, which are still focusable by script. Without it, a keyboard user must press Tab once per tab.