Hooks & State — Beginner React challenge.
Build a classic FAQ-style accordion where clicking a section's header expands its content — but opening a new section always closes whatever was open before. Only one section can ever be expanded at once.
Requirements
- Render one header (data-testid="accordion-header") per section, always visible regardless of open state.
- Clicking a closed section's header opens it, rendering its content inside data-testid="accordion-content".
- Clicking an already-open section's header closes it.
- Clicking a different section's header closes the currently open section and opens the new one.
- At most one data-testid="accordion-content" element exists in the DOM at any time.
Signature
function Accordion({ sections }: { sections: { id: number; title: string; content: string }[] }): JSX.ElementExample
<Accordion sections={[{ id: 1, title: "Q1", content: "A1" }, { id: 2, title: "Q2", content: "A2" }]} />
// click Q1's header ⇒ A1 shows
// click Q2's header ⇒ A1 hides, A2 shows
// click Q2's header again ⇒ A2 hides, nothing openConstraints
- Track the open section using a single piece of state (e.g. the open section's id, or null when none are open) — do not use a per-section boolean map.
- sections is a plain array; do not mutate it.