Courses / React 19: From Components to Production / Chapter 22
Module 11 · Advanced Component Patterns · Chapter 22 of 30
Compound Components: Parts That Share State Through Context
Builds on Components: Props, Children, Conditions, Lists and Keys, Advanced Hooks: Refs, Reducers, Context, Layout Effects and Custom Hooks, Rendering Internals and Performance: Fiber, Memo and the Compiler and Testing React: Components, Hooks, Network and End-to-End. Next up: Control Props: Components That Work Controlled or Uncontrolled.
Part 1 · Why reusable components need patterns
One prop per request
A state university's exam-results portal has a page of frequently asked questions, and every department wants it to look and behave a little differently. This chapter builds the accordion for that page so that departments can change it without asking for new props.
An accordion is a list of headings, each of which shows or hides a section of content. The first version of the portal's accordion takes the questions as data and decides everything else itself. Its props arrived one request at a time.
type FaqAccordionProps = { items: Faq[] defaultOpenIds?: string[] onChange?: (openIds: string[]) => void allowMultiple?: boolean headingLevel?: 2 | 3 | 4 showNumbers?: boolean showNewBadge?: boolean iconPosition?: 'left' | 'right' headerClassName?: string panelClassName?: string renderQuestion?: (item: Faq, open: boolean) => ReactNode disabledIds?: string[] footer?: ReactNode }
The props of the first accordion.
Thirteen props, and each one answers a real request. The School of Engineering wanted numbers before questions, so showNumbers appeared. Commerce wanted a "new" tag on recent answers, which added showNewBadge and the isNew field. Arts wanted one open question at a time, so allowMultiple arrived. The icon moved, a footer was added, and one department wanted its own markup for the question text, which became renderQuestion.
A test rendered the component with every prop set and printed the markup.
props passed: 13 <div><div><h3 class="faq-h"><button type="button" aria-expanded="true">- 1. Where do I download my marksheet? (new)</button></h3><div class="faq-p">From the Results tab.</div></div><div><h3 class="faq-h"><button type="button" aria-expanded="false">+ 2. What does revaluation cost?</button></h3><div hidden="" class="faq-p">Rs 500 per paper.</div></div><p>Still stuck? Write to the exam cell.</p></div>
Real run in jsdom. The test passed 13 props. Long lines are wrapped to fit.
It works, and every department that asks for something new needs a change to this one file.
Where the cost shows
The first cost is that options interact. allowMultiple={false} says only one question may be open, and defaultOpenIds can name two. Nothing in the component's types forbids that pair, so a test rendered it.
allowMultiple=false with two default ids -> true,true
Real run in jsdom: allowMultiple is false, two ids are open by default.
Both opened. The component's author never decided what that combination means, and with thirteen props the combinations multiply quickly. The three booleans, the icon position and the heading level alone allow 2 x 2 x 2 x 2 x 3 = 48 combinations, and a department that finds a broken one files another request. A test suite that wants confidence in every pair has to render each of them.
The second cost is that the component owns the markup. A caller who needs a link inside a header, a heading level that fits the page or a different element for the panel cannot get it without a new prop. The third is that a caller cannot reach into the structure to add its own behaviour, for example to log which question was opened.
The idea behind the fix has an old name in software design: inversion of control. Instead of the component calling the shots through configuration, it hands the decisions back to its user. A function that accepts a callback does this for behaviour. For a user interface component, handing control back means letting the caller arrange the pieces and keeping only what must stay consistent inside the component.
The compound components pattern
Compound components is the name for a set of components that work together and share state without the caller wiring it. The parent owns the state, and the children read it from context, so the caller writes the structure and the parts stay in step. HTML has the same idea: a <select> and its <option> elements only make sense together, and the <select> coordinates the selection.
The portal's accordion becomes four components: Accordion holds the state, Accordion.Item marks one question, and Accordion.Header and Accordion.Panel are its two halves. The caller writes the markup.
<Accordion defaultOpenItems={['marksheet']}>
<Accordion.Item value="marksheet">
<Accordion.Header>
Where do I download my marksheet?
</Accordion.Header>
<Accordion.Panel>From the Results tab.</Accordion.Panel>
</Accordion.Item>
<Accordion.Item value="reval">
<Accordion.Header>What does revaluation cost?</Accordion.Header>
<Accordion.Panel>Rs 500 per paper.</Accordion.Panel>
</Accordion.Item>
</Accordion>How a department will use it.
A numbered list, a footer or a link in a header is now ordinary JSX that the caller writes.
Why did the first accordion let allowMultiple={false} and two default open ids coexist?
- The props are independent options and nothing connects them. The run rendered both items open.
What does inversion of control mean for a component like this?
- The component hands decisions back to its caller. The caller arranges the headers and panels, and the component keeps only the shared state.
Which part of the compound accordion owns the open state?
Accordion, the parent. Its children read the state from context.
Part 2 · Building an accordion from parts
Two contexts for two levels
The parent has to share two kinds of information. Everything below Accordion needs the set of open items and a way to toggle one. Everything inside one Accordion.Item needs that item's value, whether it is open, and the two ids that link its header to its panel. That is two levels, so the build uses two contexts. The advanced hooks chapter covers how context works and how useId makes ids; this lesson uses both.
Each context gets a small hook that throws a clear error when a part is rendered outside its parent. Without it, a misplaced header would fail later with a confusing message about reading a property of null.
type AccordionValue = { openItems: string[] toggleItem: (value: string) => void } type ItemValue = { value: string open: boolean headerId: string panelId: string } const AccordionContext = createContext<AccordionValue | null>(null) const ItemContext = createContext<ItemValue | null>(null)
Types and contexts. The trace(...) lines in the lab files are left out.
function useAccordion(part: string) { const ctx = useContext(AccordionContext) if (!ctx) throw new Error(`<${part}> must be rendered inside <Accordion>`) return ctx } function useItem(part: string) { const ctx = useContext(ItemContext) if (!ctx) throw new Error( `<${part}> must be rendered inside <Accordion.Item>`, ) return ctx }
The two hooks that guard against a missing parent.
The root and the item
Accordion keeps the open values in state and offers a toggle. It renders no element of its own, only the provider, so the caller decides what wraps the items.
type RootProps = { defaultOpenItems?: string[]; children: ReactNode } function Root({ defaultOpenItems = [], children }: RootProps) { const [openItems, setOpenItems] = useState(defaultOpenItems) const toggleItem = (value: string) => setOpenItems((cur) => cur.includes(value) ? cur.filter((v) => v !== value) : [...cur, value], ) return ( <AccordionContext value={{ openItems, toggleItem }}> {children} </AccordionContext> ) }
The root. Its value is a new object on every render.
Two details. The state is a list of strings, not one string, because an FAQ may have several questions open at once. And the toggle uses the updater form of the state setter so two quick toggles never lose each other. The value passed to the provider is a new object on every render of Accordion, so every part that reads the context renders again whenever the root does, whether or not the open list changed.
Accordion.Item reads the open list, works out whether its own value is in it, and builds the ids. Ids come from useId, so two accordions on one page never share ids. The item publishes what it knows through the second context and renders a plain div. Extra props go straight to that div, so callers can add a class name or a data- attribute.
function Item({ value, ...rest }: ComponentProps<'div'> & { value: string }) { const { openItems } = useAccordion('Accordion.Item') const base = useId() const item = { value, open: openItems.includes(value), headerId: `${base}-header`, panelId: `${base}-panel`, } return ( <ItemContext value={item}> <div data-state={item.open ? 'open' : 'closed'} {...rest} /> </ItemContext> ) }
The item.
Header and panel
The two halves read the item context. The header is a button inside a heading and calls the toggle with its item's value. The panel is hidden when its item is closed. The last line attaches the four components under one name so callers write Accordion.Item and import one thing.
function Header({ children }: { children: ReactNode }) { const { toggleItem } = useAccordion('Accordion.Header') const item = useItem('Accordion.Header') return ( <h3> <button type="button" id={item.headerId} aria-expanded={item.open} aria-controls={item.panelId} onClick={() => toggleItem(item.value)} > {children} </button> </h3> ) }
The header.
function Panel(props: ComponentProps<'div'>) { const item = useItem('Accordion.Panel') return ( <div id={item.panelId} role="region" aria-labelledby={item.headerId} hidden={!item.open} {...props} /> ) } export const Accordion = Object.assign(Root, { Item, Header, Panel })
The panel and the export.
Object.assign(Root, { Item, Header, Panel }) copies the three components onto the root function as properties. TypeScript infers the combined type, so Accordion.Item is checked like any component.
Running it
A test rendered the usage example from the previous lesson with the first question open, clicked the second header, then the first, and read each button's aria-expanded after every step.
initial Where do I download my marksheet? -> aria-expanded=true What does revaluation cost? -> aria-expanded=false after clicking the second header Where do I download my marksheet? -> aria-expanded=true What does revaluation cost? -> aria-expanded=true after clicking the first header Where do I download my marksheet? -> aria-expanded=false What does revaluation cost? -> aria-expanded=true
Real run in jsdom with Testing Library's user-event.
The two items opened and closed independently, as the list-of-strings state allows. A second test rendered parts outside their parents and printed the thrown messages.
threw: <Accordion.Header> must be rendered inside <Accordion> threw: <Accordion.Header> must be rendered inside <Accordion.Item>
Real run. The first render has no Accordion; the second has no Item.
The messages name the part and its missing parent, which is what a developer needs to fix the mistake in seconds. The markup the first test printed shows the generated ids and the link between each header and its panel:
<div data-state="closed"><h3><button type="button" id="_r_0_-header" aria-expanded="false" aria-controls="_r_0_-panel">Where do I download my marksheet?</button></h3><div id="_r_0_-panel" role="region" aria-labelledby="_r_0_-header" hidden="">From the Results tab.</div></div>
The markup after the last click, formatted for the page.
Everything the caller did not write, the ids, the ARIA attributes and the hidden state, comes from the parts.
Why does the item use its own context instead of the accordion context?
- The item's value, open state and ids belong to one item. Header and panel of the same item read them, and other items are unaffected.
What does useId give the accordion that a hard-coded id would not?
- A unique id per item per instance, so two accordions or two items never share ids. The run's ids looked like
_r_0_-header.
Part 3 · Keeping renders down
The cost of an unstable value
The first accordion works, but it re-renders more than it needs to. The cause is the provider's value. A context consumer renders again whenever the value changes, compared with Object.is, and the root builds a new object every time it renders. If the page re-renders Accordion for a reason unrelated to the accordion, every consumer pays for it. The advanced hooks chapter measured the same effect on a single context; here it is applied to a whole family of parts.
The test page below holds an unrelated counter next to the accordion. Each question is a memoised row component, so a parent render alone cannot reach the parts. Only a context change can.
function makePage(Accordion: Acc) { const Row = memo(function Row(p: { value: string q: string a: string }) { return ( <Accordion.Item value={p.value}> <Accordion.Header>{p.q}</Accordion.Header> <Accordion.Panel>{p.a}</Accordion.Panel> </Accordion.Item> ) }) return function Page() { const [n, setN] = useState(0) return ( <> <button onClick={() => setN(n + 1)}>unrelated {n}</button> <Accordion> <Row value="a" q="Marksheet?" a="Results tab." /> <Row value="b" q="Revaluation?" a="Rs 500." /> <Row value="c" q="Supplementary?" a="In July." /> </Accordion> </> ) } }
The page used for counting. Row is memoised.
Each component pushes its name onto a log array when it renders; those one-line trace calls are left out of the code shown in this chapter. The test mounts the page, clicks the unrelated counter, then opens the second question, and prints what rendered each time.
mount: 10 renders
unrelated click: Accordion, Item a, Header a, Panel a, Item b,
Header b, Panel b, Item c, Header c, Panel c
toggle b: Accordion, Item a, Header a, Panel a, Item b, Header b,
Panel b, Item c, Header c, Panel cReal run in jsdom, first accordion. Long lines are wrapped to fit.
Clicking the unrelated counter re-rendered ten components, and so did opening one question. Every part sat below a context whose value changed identity on each render.
Memoising and splitting
Two changes fix this. First, build each context value with useMemo, so its identity changes only when its contents do. Second, split the accordion context into one for state and one for actions. The toggle function never changes, so components that only call it, such as headers, do not need to render when the open list changes.
function Root({ defaultOpenItems = [], children }: RootProps) { const [openItems, setOpenItems] = useState(defaultOpenItems) const toggleItem = useCallback((value: string) => { setOpenItems((cur) => cur.includes(value) ? cur.filter((v) => v !== value) : [...cur, value], ) }, []) const state = useMemo(() => ({ openItems }), [openItems]) const actions = useMemo(() => ({ toggleItem }), [toggleItem]) return ( <ActionsContext value={actions}> <StateContext value={state}>{children}</StateContext> </ActionsContext> ) }
The root after the change.
The toggle is wrapped in useCallback with no dependencies, which is safe because it uses the updater form of the setter. The two memoised values change only when openItems changes. The item now builds its context value with useMemo too, keyed on its value, its open flag and its id.
function need<T>(ctx: T | null, message: string): T { if (!ctx) throw new Error(message) return ctx } const useAccordionState = (part: string) => need( useContext(StateContext), `<${part}> must be rendered inside <Accordion>`, ) const useAccordionActions = (part: string) => need( useContext(ActionsContext), `<${part}> must be rendered inside <Accordion>`, ) const useItem = (part: string) => need( useContext(ItemContext), `<${part}> must be rendered inside <Accordion.Item>`, )
The hooks after the split, with a shared helper.
The header reads actions from one context and its own item from another, and does not read the state at all. The panel reads only its item.
What the numbers say
The same test ran on the second version.
mount: 10 renders
unrelated click: Accordion
toggle b: Accordion, Item a, Item b, Header b, Panel b, Item cReal run in jsdom, memoised and split.
The unrelated click re-rendered only Accordion, which re-rendered because its parent did. It created no new context values, and the memoised rows kept their children out of the render. Opening question b rendered Accordion, the three items, and the header and panel of b alone. The items still render because they read the open list, but the headers and panels of a and c skip.
Watch for which parts render when question b is opened
Read it as steps
The three items read the open list; only b's header and panel render after them
The three items rendering on every toggle is the price of keeping the open list in one array that each item searches. For a short FAQ it is cheap. For a long list, the client stores with selectors, from the architecture chapter, let each item subscribe to its own flag and skip entirely. Measure before reaching for it, and remember that most of the gain here, from ten renders to one on unrelated updates, came from two useMemo calls and one useCallback.
Part 4 · Change callbacks without effects
Telling the parent what happened
The portal's analytics team wants to know which question a student opens. The accordion needs an onOpenItemsChange prop, a function it calls with the new list of open values. The caller supplies it, and the accordion stays uncontrolled: it keeps the state, and the callback is a notification.
The tempting implementation is an effect that watches the state and calls the callback when it changes. It looks tidy: one place, always in sync. The lab wrote exactly that.
function Root({ defaultOpenItems = [], onOpenItemsChange, children, }: RootProps) { const [openItems, setOpenItems] = useState(defaultOpenItems) useEffect(() => { onOpenItemsChange?.(openItems) }, [openItems, onOpenItemsChange])
The start of the effect version's root.
The page that uses it passes an inline callback and also has an unrelated counter, which is what real pages look like. A test measured how many times the callback ran after mount, after an unrelated render, and after one click, with and without StrictMode.
effect: calls after mount 1, after an unrelated render 2, after one click 3; last ["a"] effect (StrictMode): calls after mount 2, after an unrelated render 3, after one click 4; last ["a"]
Real run in jsdom: the effect version, without and with StrictMode. Long lines are wrapped to fit.
The callback ran on mount, though nobody had opened anything, and again after an unrelated render, because the inline function is a new object each time and the effect lists the callback as a dependency. One real click produced a third call. In StrictMode the mount effect ran twice. The analytics would be filled with events that never happened.
Removing the callback from the dependency list would hide the extra calls after unrelated renders, but then the effect would keep calling the callback from the first render. The real problem is the design: a change callback is a reaction to something the user did, and the place for that is the event handler that did it.
Calling it from the handler
The toggle already runs when the user clicks. It can compute the next list, set the state, and call the callback, all in one place. Two things need care. The callback must not be called inside the state updater function, because React may call updater functions twice in development to catch impure code. A test confirmed it.
callback inside the updater, StrictMode, one click: 2 callsReal run in jsdom: a callback called inside setOpen's updater, StrictMode.
So the toggle must read the current list outside the setter. But reading openItems directly would make toggleItem depend on it, and the toggle would change on every click, undoing the work of the last lesson. The answer is a ref that always holds the latest list and callback. The ref is written in an effect that runs after each render, and also by the toggle itself so that two toggles in the same event stay correct.
function Root({ defaultOpenItems = [], onOpenItemsChange, children, }: RootProps) { const [openItems, setOpenItems] = useState(defaultOpenItems) const latest = useRef({ openItems, onOpenItemsChange }) useEffect(() => { latest.current = { openItems, onOpenItemsChange } }) const toggleItem = useCallback((value: string) => { const { openItems: cur, onOpenItemsChange: notify } = latest.current const next = cur.includes(value) ? cur.filter((v) => v !== value) : [...cur, value] latest.current = { openItems: next, onOpenItemsChange: notify } setOpenItems(next) notify?.(next) }, []) const state = useMemo(() => ({ openItems }), [openItems]) const actions = useMemo(() => ({ toggleItem }), [toggleItem]) return ( <ActionsContext value={actions}> <StateContext value={state}>{children}</StateContext> </ActionsContext> ) }
The final root. The callback runs in the handler.
handler: calls after mount 0, after an unrelated render 0, after one click 1; last ["a"] handler (StrictMode): calls after mount 0, after an unrelated render 0, after one click 1; last ["a"]
Real run in jsdom with the final version, same test page. Long lines are wrapped to fit.
No call on mount, none for an unrelated render, one for the click, in StrictMode as well. A last test clicked a, b, then a again, and the callback received each new list:
[["a"],["a","b"],["b"]]
Real run: the lists the callback received.
The render counts from the previous lesson held for this version too. The test that printed them for the final file shows unrelated click: Accordion and the same six components for opening b.
Two toggles in one event
The ref write inside toggleItem matters when one handler toggles twice before React renders again. A test added a small part that calls toggleItem('a') and then toggleItem('b') in a single click, once with the toggle writing the ref and once with that line removed.
toggle writes the ref: callback saw [["a"],["a","b"]] | expanded true,true toggle does not write the ref: callback saw [["a"],["b"]] | expanded false,true
Real run in jsdom: one click on a button that toggles a and then b. Long lines are wrapped to fit.
Without the write, the second call still read the empty list from the last render, asked for ["b"] and lost a. With it, the second call started from the list the first call had just produced, the way a chain of updater functions would.
The rule behind the fix is general. A callback that reports a user action belongs in the handler of that action. An effect is for synchronising with something outside React, and calling the parent is not that.
Why did the effect version call onOpenItemsChange on mount?
- The effect ran after the first render with the initial list, and nothing stops it. The run counted one call before any click.
Why not call the callback inside the state updater?
- React may call updaters twice in development. The StrictMode run called the callback twice for one click.
How does the toggle stay stable while still reading the latest list?
- It reads the list and the callback from a ref that is updated after each render and by the toggle itself, so its own identity never changes.
Part 5 · Styling hooks and flexible structure
What callers need to reach
A department wants its accordion to look different, and a developer wants to log or veto a click. The parts already allow most of it through three small decisions.
First, extra props pass through. Item and Panel spread the rest of their props onto the element they render, and Header spreads them onto its button, so callers add className, data- attributes or an aria- label without a new prop.
Second, state is exposed as a data attribute. Each part writes data-state="open" or data-state="closed", so a stylesheet can target [data-state='open'] without any React code, and no extra prop carries the state to the style.
Third, the header composes handlers instead of replacing them. It runs the caller's onClick first and toggles unless the caller called preventDefault. A test gave one header a tracking handler and another a handler that cancels.
type HeaderProps = ComponentProps<'button'> & { level?: 2 | 3 | 4 | 5 | 6 } function Header({ level = 3, onClick, ...rest }: HeaderProps) { const { toggleItem } = useAccordionActions('Accordion.Header') const item = useItem('Accordion.Header') const Heading = `h${level}` as 'h3' return ( <Heading> <button type="button" {...rest} id={item.headerId} aria-expanded={item.open} aria-controls={item.panelId} data-state={item.open ? 'open' : 'closed'} onClick={(event) => { onClick?.(event) if (!event.defaultPrevented) toggleItem(item.value) }} /> </Heading> ) }
The header with rest props, data-state and handler composition.
Tracked expanded: true | Vetoed expanded: false | caller handlers ran:
track, veto
data-state: div=open button=open div=open div=closed button=closed
div=closedReal run in jsdom. Long lines are wrapped to fit.
Both caller handlers ran. The tracked question opened, the vetoed one stayed closed, and every part carried its data-state. The attribute list shows item, button and panel in order for each question.
Why context and not cloned children
Another way to build this is to let the root loop over its children and give each one the props it needs. React's Children.map walks the children and cloneElement copies an element with extra props. The lab wrote that version.
export function CloneAccordion({ children }: { children: ReactNode }) { const [openItems, setOpenItems] = useState<string[]>([]) const toggle = (value: string) => setOpenItems((cur) => cur.includes(value) ? cur.filter((v) => v !== value) : [...cur, value], ) return ( <div> {Children.map(children, (child) => isValidElement<ItemProps>(child) ? cloneElement(child, { open: openItems.includes(child.props.value), onToggle: () => toggle(child.props.value), }) : child, )} </div> ) }
The same accordion built with cloneElement.
It works while every child is a direct CloneItem. A real page wraps things. A department might put a "pinned" badge around an item with a small component.
clone: first true second (wrapped in a component) null errors: [] context: first true second (wrapped) true
Real run in jsdom. The second item is wrapped in a Pinned component.
The clone version opened the first item and did nothing for the wrapped one: aria-expanded was missing altogether, because the clone gave its extra props to Pinned, which ignored them. React printed no warning or error. The context version opened both, because it never depended on how the parts were nested.
The react.dev page for cloneElement agrees. It calls the function uncommon and says it can lead to fragile code, adds that it makes data flow harder to trace, and lists three alternatives: a render prop, context and a custom hook. This accordion took the second. Context also lets any depth of nesting, a fragment, a layout div or a wrapper component, sit between the parts.
Spread order decides who wins
Spreading rest props raises one question: what happens when a caller passes a prop that the part also sets? The answer is the order of the spread. The first version's Panel sets its id first and spreads the caller's props after it, so the caller's value wins. A test passed id="mine" to a panel in the first version and in the final one.
first version: aria-controls _r_2_-panel | panel id mine final version: aria-controls _r_3_-panel | panel id _r_3_-panel
Real run in jsdom. The numbers in the generated ids depend on how many components used useId earlier in the file.
In the first version the header still pointed at the generated id, so the link between header and panel was silently broken. The final version spreads the caller's props first and sets its own wiring after them, so the generated id stays and the caller's id is ignored. Item, Header and Panel all follow that order now, and Header also composes the caller's onClick into its own handler. So the rule in these parts is simple: the caller's props are applied first, and the part's own wiring props are applied after them and win.
How does a stylesheet know whether an item is open without a prop?
- Each part writes
data-state="open"or"closed", and a selector such as[data-state='open']targets it.
What did the cloned version do when an item was wrapped in another component?
- It gave the props to the wrapper, so the item never toggled. The run showed no
aria-expandedfor it and no error.
What did the header do when the caller's onClick called preventDefault?
- It skipped the toggle. In the run the vetoed question stayed closed and both caller handlers ran.
Part 6 · Accessible by default
What the pattern asks for
Compound components let the author put accessibility into the parts once, so every caller gets it. The W3C's ARIA Authoring Practices Guide (APG) describes the accordion pattern. Its page says the header title sits in a button, and that each button is wrapped in an element with the heading role and a level that fits the page. The button reports aria-expanded as true when the panel is visible and false when hidden, and aria-controls points to the panel. Each panel may have role="region" and an aria-labelledby that points to its button, but the page says to leave the region role off when many panels can be open at once, roughly more than six, to avoid a proliferation of landmarks. It adds that the role is especially helpful to screen reader users when panels contain headings or a nested accordion.
The keyboard section lists Enter and Space to expand or collapse and Tab and Shift+Tab to move between focusable elements. The page does not list arrow keys, so this accordion adds none: its headers are native buttons in the normal tab order.
The accordion built here follows that description. Header wraps a button in a heading whose level the caller sets with the level prop, aria-expanded and aria-controls come from the item context, and Panel carries the region role with aria-labelledby. A native button gives Enter and Space for free.
Checking it with role queries
Testing Library finds elements by role and accessible name, which is close to what assistive technology uses. The test below renders two questions and asks for them the way a screen reader user would meet them.
headings: [ 'Where is my marksheet?', 'What does revaluation cost?' ] button expanded: false regions found while closed: 0 regions found with hidden: true: 2 open region name from button, text: From the Results tab. aria-controls points at the region: true
Real run in jsdom, first test.
Both headings were found at level 3 by their text. The closed panels do not appear as regions, because the hidden attribute puts them outside what the role query considers accessible, and they appear only when the query asks for hidden elements. After a click, the region was found by the name of its button, and the button's aria-controls matched the region's id.
Choosing the heading level
The heading level is the one decision the accordion cannot make, because it depends on where the FAQ sits in the page. An accordion under a level 3 section heading needs level 4 headers, otherwise the page outline skips or repeats a level and screen reader users who navigate by headings get a confusing map. The level prop passes the choice to the caller, with 3 as the default. A test rendered a header at level 4.
level 4 headings: [ 'H4' ] | level 3 headings: 0
Real run in jsdom.
The element became an h4, and a query for level 3 found nothing. The caller decides the level and the accordion keeps the structure around it correct.
Checking the keyboard
A second test pressed Tab once, then Enter, Space, Tab again and Enter, and read the state after each key.
focus after one Tab: true after Enter: true after Space: false Tab moves to the second header: true second after Enter: true
Real run in jsdom, second test.
One Tab reached the first header. Enter opened it and Space closed it, then Tab moved to the second header, where Enter opened it. All of that came from the native button, and the accordion added only the wiring.
What the test does not show is how a screen reader announces the result, or how the page looks. Those need a browser and a person. The APG page is the reference for what to check by hand, and the test above guards against regressions in the markup, which is the part that tends to break when someone restyles a component.
Why does the closed panel not appear in a role query for regions?
- The
hiddenattribute makes it inaccessible to the query. The run found 0 regions while closed and 2 when asking for hidden ones.
Which keys toggled an item in the run, and where do they come from?
- Enter and Space. They come from the native
button, which the header renders.
When does the APG page suggest leaving off role="region" on panels?
- When many panels can be open at once, roughly more than six, to avoid too many landmark regions.
All chapters · Previous: Security, Performance Budgets and Delivery