Accordion

MediumDOM Manipulation20 min6 tests

Build a three-section accordion where each header button toggles its own collapsible panel independently, multiple panels can be open at once, all start closed, and closed panels are removed from the DOM.

Create an Accordion with three sections. Each section is made up of a header button and a collapsible panel of content.

Behavior:

  • All panels are closed initially. A closed panel must NOT be rendered in the document (it is removed, not just visually hidden).
  • Clicking a section's header button toggles ONLY that section's panel — opening it if closed, closing it if open.
  • Sections are independent: opening one does not close another. Any number of panels (zero to three) can be open at the same time.
  • Each header button exposes its open/closed state via the aria-expanded attribute ("true" when its panel is open, "false" when closed).

The three sections are provided for you as data (a title and body for each). Your job is to render the headers and wire up the toggle behavior so each panel appears/disappears on its own.

Requirements

  • Render exactly three section header buttons, one per item in the provided data, each labeled with that section's title.
  • Each header button must have aria-expanded set to "false" when its panel is closed and "true" when open.
  • All three panels must be closed on initial render (no panel content present in the document).
  • Clicking a header button opens its panel (renders its body text); clicking it again closes that panel (removes the body text from the document).
  • Toggling one section must not affect the open/closed state of any other section — multiple panels may be open simultaneously.
  • Closed panels must be absent from the DOM, not merely hidden with CSS.
Hints (4)
  1. Track open state per section with an array or object of booleans in useState, e.g. one boolean per section index.
  2. Conditionally render each panel: only output the panel element when that section's boolean is true (use {isOpen && <div>...</div>}), so closed panels are truly absent from the DOM.
  3. Set aria-expanded={isOpen ? 'true' : 'false'} on each header button (or aria-expanded={isOpen} — React serializes the boolean to the string).
  4. The click handler should flip only the clicked index's boolean, copying the rest of the state unchanged so other sections are untouched.

Topics

  • React
  • DOM Manipulation

Asked at

BrowserStack · Myntra · Zomato · Postman · Nykaa · Razorpay

Join Us
blur