Sub topic 13
Accessibility in Compound Components
This chapter assumes you can build a context-based compound component, as in the previous chapters. It covers the roles and attributes a Tabs component needs so that screen readers and keyboards can use it.
Why compound components need extra care
A compound component splits one widget across several elements. A screen reader user cannot see that a button and a panel belong together. You have to state that relationship in the markup. Roles and ARIA attributes do this. ARIA (Accessible Rich Internet Applications) is a set of HTML attributes that describe widgets to assistive technology.
The Tabs example already sets role="tab", aria-selected and role="tabpanel". Three things are missing:
- A
tablistrole on the container that holds the tabs. - Links between each tab and its panel, using
id,aria-controlsandaria-labelledby. - Keyboard support, so that only the active tab is in the page's tab order.
Linking tabs and panels
Both subcomponents already receive a value. Use it to derive matching ids. Add a small helper next to useTabs:
const tabId = (value) => `tab-${value}`;
const panelId = (value) => `panel-${value}`;Then update Tab and Panel:
function Tab({ value, children }) {
const { value: active, setValue } = useTabs();
const selected = active === value;
return (
<button
role="tab"
id={tabId(value)}
aria-selected={selected}
aria-controls={panelId(value)}
tabIndex={selected ? 0 : -1}
onClick={() => setValue(value)}
>
{children}
</button>
);
}
function Panel({ value, children }) {
const { value: active } = useTabs();
if (active !== value) return null;
return (
<div role="tabpanel" id={panelId(value)} aria-labelledby={tabId(value)} tabIndex={0}>
{children}
</div>
);
}aria-controls points from the tab to its panel. aria-labelledby points back, so the panel is announced with the tab's text as its name. tabIndex={-1} removes inactive tabs from the Tab key sequence. In the common tabs pattern, arrow keys move between tabs instead.
One caveat: aria-controls references an element that does not exist while its panel is unmounted. Some screen readers ignore the broken reference. It is harmless, but you can render hidden panels with the hidden attribute if you want the reference to always resolve.
Using the tablist role
The consumer writes the container, so the tablist role belongs there. You could also export a Tabs.List subcomponent that sets it. Either way, the container needs role="tablist", as the earlier example shows.
Exercise
A Panel is rendered with aria-labelledby={tabId(value)}. What does a screen reader do with this attribute, and what must be true of the tab for it to work?
Show answer
The screen reader uses the text of the element whose id matches as the panel's accessible name. The tab must have id={tabId(value)} with the same value, so the ids match.