← Back to React, page 4

react-0067 · Easy fresher

Build an accordion where one section is open at a time. How do you model the state and make it accessible?

Store the id of the open section, or null, in one state variable. Clicking a header sets it to that id, or to null if it is already open. Render each header as a button with aria-expanded and aria-controls, and the panel only when open. Storing one id instead of a boolean per item guarantees a single open section and keeps the component simple.

Full answer

The state question decides the design. If each item had its own open boolean, the parent could not enforce "one at a time" without extra code. One openId in the parent does it by construction: it is either null or the id of the open section, so two sections can never be open together.

The header is a button, so it works with keyboard and screen readers. It gets aria-expanded={isOpen} and aria-controls pointing at the panel id. The panel has the matching id and is rendered only when open, or hidden with the hidden attribute if you want to keep its state.

The click handler toggles: setOpenId(isOpen ? null : id). If you need to allow several open sections, change the state to a Set or an array of ids and toggle membership immutably.

Extensions that come up in interviews. Make the component reusable by taking items as props. Support a default open item with an initial value. Add keyboard navigation between headers with arrow keys. Animate height with CSS grid or the hidden="until-found" attribute. Use native <details> and <summary> for simple cases, which gives the behaviour with no JavaScript, and a name attribute on details can group them into an exclusive accordion in current browsers.

IDs for aria-controls should be unique, so build them from the item id or use useId when the component can be rendered several times.

jsx
import { useState } from 'react';

const items = [
  { id: 'props', title: 'What are props?', body: 'Inputs passed from a parent component.' },
  { id: 'state', title: 'What is state?', body: 'Memory owned by a component.' },
  { id: 'keys', title: 'Why keys?', body: 'They identify list items between renders.' },
];

export default function Accordion() {
  const [openId, setOpenId] = useState(null);

  return (
    <div>
      {items.map((item) => {
        const isOpen = openId === item.id;
        return (
          <section key={item.id}>
            <h3>
              <button
                aria-expanded={isOpen}
                aria-controls={'panel-' + item.id}
                onClick={() => setOpenId(isOpen ? null : item.id)}
              >
                {item.title}
              </button>
            </h3>
            {isOpen && <div id={'panel-' + item.id}>{item.body}</div>}
          </section>
        );
      })}
    </div>
  );
}

The check pressed each header once, so the last one is open and the others closed. Rendered result: <div><section><h3><button aria-expanded="false" aria-controls="panel-props">What are props?</button></h3></section><section><h3><button aria-expanded="false" aria-controls="panel-state">What is state?</button></h3></section><section><h3><button aria-expanded="true" aria-controls="panel-keys">Why keys?</button></h3><div id="panel-keys">They identify list items between renders.</div></section></div>

Key points

  • One openId state value enforces a single open section.
  • Headers are buttons with aria-expanded and aria-controls.
  • The click handler toggles between the id and null.
  • Use a set of ids for multiple open sections.
  • Native details and summary are a simple alternative.

Common mistakes

  • Keeping a boolean per item and letting several open together by accident.
  • Using div elements with click handlers as headers.
  • Forgetting aria-expanded, so screen readers cannot tell the state.
  • Using the array index as the id when the list can change.
  • Not allowing the open section to close again.

Follow-ups

  • How would you allow multiple sections open at once?
  • How would you add arrow-key navigation between headers?
  • When is the native details element enough?

Tips

  • Explain why one openId beats many booleans.
  • Include the ARIA attributes in the first version. It shows habits.
  • Mention details and summary as the zero-JavaScript option.