76Build an accessible accordion with keyboard navigation
mediumAbout 35 minutesCodingreactaccessibilitykeyboardui
Problem
Build <Accordion items={items} allowMultiple={false} defaultOpen={[]} />, where items is an array of { id, title, content }. Follow the WAI-ARIA accordion pattern:
- Each header is
<h3><button id="{id}-header" aria-expanded="true|false" aria-controls="{id}-panel">{title}</button></h3>. - Each panel is
<div id="{id}-panel" role="region" aria-labelledby="{id}-header" hidden={!open}>{content}</div>.
Requirements
- Clicking a header (or pressing
EnterorSpaceon it) toggles its panel. - With
allowMultiple={false}, opening one panel closes the others. Withtrue, panels open independently. defaultOpenlists the ids that start open.- Keyboard:
ArrowDownandArrowUpmove focus to the next or previous header, wrapping around;HomeandEndmove to the first and last header.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
App.jsxReact + DOM
Step-by-step
useState(() => new Set(defaultOpen)). A Set handles both modes: in single mode it holds at most one id.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 4 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.