javascript
63 lines · 8 steps
Building a compound Accordion in React
Two React contexts let an Accordion share open state and per-item IDs across loosely coupled subcomponents.
Explained by
highlit
1import { createContext, useContext, useState, useId } from "react";
2
3const AccordionContext = createContext(null);
4const ItemContext = createContext(null);
5
6export function Accordion({ children, allowMultiple = false }) {
7 const [openIds, setOpenIds] = useState(() => new Set());
8
9 const toggle = (id) => {
10 setOpenIds((prev) => {
11 const next = new Set(allowMultiple ? prev : []);
12 if (prev.has(id)) next.delete(id);
13 else next.add(id);
14 return next;
15 });
16 };
17
18 return (
19 <AccordionContext.Provider value={{ openIds, toggle }}>
20 <div className="accordion">{children}</div>
21 </AccordionContext.Provider>
22 );
23}
24
25Accordion.Item = function AccordionItem({ children }) {
26 const id = useId();
27 return (
28 <ItemContext.Provider value={id}>
29 <div className="accordion-item">{children}</div>
30 </ItemContext.Provider>
31 );
32};
33
34Accordion.Header = function AccordionHeader({ children }) {
35 const id = useContext(ItemContext);
36 const { openIds, toggle } = useContext(AccordionContext);
37 const isOpen = openIds.has(id);
38
39 return (
40 <button
41 type="button"
42 className="accordion-header"
43 aria-expanded={isOpen}
44 aria-controls={`panel-${id}`}
45 onClick={() => toggle(id)}
46 >
47 {children}
48 <span aria-hidden>{isOpen ? "\u2212" : "+"}</span>
49 </button>
50 );
51};
52
53Accordion.Panel = function AccordionPanel({ children }) {
54 const id = useContext(ItemContext);
55 const { openIds } = useContext(AccordionContext);
56 if (!openIds.has(id)) return null;
57
58 return (
59 <div id={`panel-${id}`} role="region" className="accordion-panel">
60 {children}
61 </div>
62 );
63};
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Compound components share state through context instead of prop drilling, keeping the public API declarative.
- 2A Set in state cleanly models which items are open and toggles between single- and multi-open modes.
- 3Deriving aria-expanded and aria-controls from the same state keeps the UI and accessibility tree in sync.
Related explainers
typescript
type CountdownState = { deadline: number; onTick: (remaining: number) => void; onComplete: () => void;
A countdown timer that survives reloads
persistence
timers
localstorage
Intermediate
10 steps
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
javascript
const MAX_BATCH_SIZE = 20; const FLUSH_INTERVAL = 5000; const ENDPOINT = '/api/analytics';
Batching analytics events in the browser
batching
buffering
sendbeacon
Intermediate
10 steps
javascript
export function diffIds(current, desired) { const currentSet = new Set(current); const desiredSet = new Set(desired);
Diffing sets to sync group membership
set-operations
diffing
transactions
Intermediate
8 steps
javascript
class HistoryStack { constructor(initial = '', limit = 100) { this.past = []; this.present = initial;
Building an undo/redo history stack
undo-redo
state-management
debouncing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-compound-accordion-in-react-explained-javascript-d4c3/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.