Skip to content

Checkpoint: An Accordion API

The Course
•
20 min study

Close the earlier lessons and build this from the brief. This time the API is fixed: App.jsx already uses Accordion the way the brief describes, and useControllableState is included. Write Accordion.jsx so it works.

The brief

  • <Accordion> holds any number of <AccordionItem value title>. Several items can be open at once.
  • Uncontrolled: defaultOpen={["reducers"]} sets which items start open.
  • Controlled: open={[...]} and onOpenChange={setOpen} let the parent own the open items, and change them, as Close all from the parent does.
  • Each item's title is a <button> inside an <h3>, with aria-expanded, and aria-controls pointing at its panel, using useId. Its content is in the panel, shown only when open.
  • An AccordionItem outside an Accordion throws <AccordionItem> must be used inside <Accordion>.

Acceptance checks:

  • In the controlled accordion, opening Suspense shows Open: context, suspense. Close all from the parent closes both and shows Open: none.
  • The uncontrolled accordion starts with Reducers open, and doesn't affect the Open: line.
Your workspace React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // Build Accordion and AccordionItem so App.jsx works as written. See the brief. export function Accordion({ children }) { return <div>{children}</div>; } export function AccordionItem({ title, children }) { return ( <section> <h3>{title}</h3> <div>{children}</div> </section> ); } import { useState } from "react"; import { Accordion, AccordionItem } from "./Accordion.jsx"; export default function App() { const [open, setOpen] = useState(["context"]); return ( <main> <h1>Study notes</h1> <h2>Uncontrolled</h2> <Accordion defaultOpen={["reducers"]}> <AccordionItem value="reducers" title="Reducers">A reducer turns the state and an action into the next state.</AccordionItem> <AccordionItem value="refs" title="Refs">A ref holds a value without causing a re-render.</AccordionItem> </Accordion> <h2>Controlled</h2> <Accordion open={open} onOpenChange={setOpen}> <AccordionItem value="context" title="Context">Context passes data deep without props.</AccordionItem> <AccordionItem value="suspense" title="Suspense">Suspense shows a fallback while something loads.</AccordionItem> </Accordion> <p className="muted">Open: {open.join(", ") || "none"}</p> <button onClick={() => setOpen([])}>Close all from the parent</button> </main> ); } import { useState } from "react"; // State that a parent can control (value + onChange) or leave to the // component (defaultValue), like <input value> versus <input defaultValue>. export function useControllableState({ value, defaultValue, onChange }) { const [inner, setInner] = useState(defaultValue); const isControlled = value !== undefined; const current = isControlled ? value : inner; function setValue(next) { if (!isControlled) setInner(next); onChange?.(next); } return [current, setValue]; } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the parts

Accordion holds the open values with useControllableState, and shares them and a toggle(value) function through a context. AccordionItem reads the context to know whether it's open.

Hint 2: toggling a value in an array

Remove it if it's there, add it if it isn't: openValues.includes(value) ? openValues.filter((v) => v !== value) : [...openValues, value].

Show one solution
One solution React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { createContext, useContext, useId } from "react"; import { useControllableState } from "./useControllableState.js"; const AccordionContext = createContext(null); export function Accordion({ open, defaultOpen = [], onOpenChange, children }) { const [openValues, setOpenValues] = useControllableState({ value: open, defaultValue: defaultOpen, onChange: onOpenChange }); function toggle(value) { setOpenValues(openValues.includes(value) ? openValues.filter((v) => v !== value) : [...openValues, value]); } return ( <AccordionContext value={{ openValues, toggle }}> <div className="accordion">{children}</div> </AccordionContext> ); } export function AccordionItem({ value, title, children }) { const accordion = useContext(AccordionContext); if (accordion === null) throw new Error("<AccordionItem> must be used inside <Accordion>."); const id = useId(); const isOpen = accordion.openValues.includes(value); return ( <section className="card"> <h3 style={{ margin: 0 }}> <button className="title" aria-expanded={isOpen} aria-controls={`${id}-panel`} onClick={() => accordion.toggle(value)} > {isOpen ? "▾" : "▸"} {title} </button> </h3> {isOpen && ( <div id={`${id}-panel`} role="region" aria-label={title}> <p>{children}</p> </div> )} </section> ); } import { useState } from "react"; import { Accordion, AccordionItem } from "./Accordion.jsx"; export default function App() { const [open, setOpen] = useState(["context"]); return ( <main> <h1>Study notes</h1> <h2>Uncontrolled</h2> <Accordion defaultOpen={["reducers"]}> <AccordionItem value="reducers" title="Reducers">A reducer turns the state and an action into the next state.</AccordionItem> <AccordionItem value="refs" title="Refs">A ref holds a value without causing a re-render.</AccordionItem> </Accordion> <h2>Controlled</h2> <Accordion open={open} onOpenChange={setOpen}> <AccordionItem value="context" title="Context">Context passes data deep without props.</AccordionItem> <AccordionItem value="suspense" title="Suspense">Suspense shows a fallback while something loads.</AccordionItem> </Accordion> <p className="muted">Open: {open.join(", ") || "none"}</p> <button onClick={() => setOpen([])}>Close all from the parent</button> </main> ); } import { useState } from "react"; // State that a parent can control (value + onChange) or leave to the // component (defaultValue), like <input value> versus <input defaultValue>. export function useControllableState({ value, defaultValue, onChange }) { const [inner, setInner] = useState(defaultValue); const isControlled = value !== undefined; const current = isControlled ? value : inner; function setValue(next) { if (!isControlled) setInner(next); onChange?.(next); } return [current, setValue]; } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Check yourself

  1. When is a compound component better than a single component with many props?
  2. How does a component tell whether it's controlled or uncontrolled?
  3. When is an imperative handle the right choice, and when is a prop better?

Was this article helpful?

Your response is saved on this device.