ReactEasy

Accordion component

An accordion is a list of headers that expand and collapse their content sections. Track which items are open (one at a time or several), render each header as a button inside a heading with aria-expanded and aria-controls, and show or hide the panel. The native <details> and <summary> elements provide a no-JavaScript version, and since 2024 browsers support <details name="..."> for exclusive accordions.

Requirements

  1. Toggle an item by clicking its header (Enter and Space work automatically on buttons).
  2. Single-open or multi-open mode.
  3. ARIA: header button with aria-expanded, aria-controls, panel with role="region" and aria-labelledby.
  4. Optional animation of height and preserved content state.

State design

  • Single mode: openId: string | null.
  • Multi mode: open: Set<string>, updated immutably (new Set(prev)).
  • Controlled API (value, onValueChange) for parents that need to drive it.

Native alternative

<details name="faq"><summary>Shipping</summary><p>3-5 days</p></details>

Elements with the same name act as an exclusive group in modern browsers, and the content is findable with Ctrl+F.

Animation

Animate grid-template-rows: 0fr to 1fr, or use CSS interpolate-size: allow-keywords where supported, rather than measuring heights in JavaScript.

Code example

tsx
1import { useId, useState } from "react";
2
3type Item = { id: string; title: string; content: React.ReactNode };
4
5export function Accordion({ items, multiple = false }: { items: Item[]; multiple?: boolean }) {
6 const [open, setOpen] = useState<Set<string>>(() => new Set());
7 const baseId = useId();
8
9 function toggle(id: string) {
10 setOpen((prev) => {
11 const next = multiple ? new Set(prev) : new Set<string>();
12 if (prev.has(id)) next.delete(id);
13 else next.add(id);
14 return next;
15 });
16 }
17
18 return (
19 <div>
20 {items.map((item) => {
21 const isOpen = open.has(item.id);
22 const headerId = `${baseId}-h-${item.id}`;
23 const panelId = `${baseId}-p-${item.id}`;
24 return (
25 <div key={item.id}>
26 <h3>
27 <button id={headerId} aria-expanded={isOpen} aria-controls={panelId} onClick={() => toggle(item.id)}>
28 {item.title} {isOpen ? "−" : "+"}
29 </button>
30 </h3>
31 <div id={panelId} role="region" aria-labelledby={headerId} hidden={!isOpen}>
32 {item.content}
33 </div>
34 </div>
35 );
36 })}
37 </div>
38 );
39}
40
41// <Accordion items={[{ id: "ship", title: "Shipping", content: <p>3-5 days</p> }, { id: "ret", title: "Returns", content: <p>30 days</p> }]} />

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app