practiceadvanced
Accordion with Compound Components
You have an Accordion that receives all its configuration as props (items, activeId, onToggle). Refactor it to the Compound Components pattern: state lives inside Accordion and the subcomponents Accordion.Item, Accordion.Trigger and Accordion.Panel communicate through Context without receiving explicit props between them.
Objectives
- 1.Create a private AccordionCtx context with { active, toggle }
- 2.Accordion manages state with useState and provides the context
- 3.Accordion.Item provides its own id to a child context (ItemCtx) via a second Provider
- 4.Accordion.Trigger reads the item id from ItemCtx and calls toggle on click
- 5.Accordion.Panel only renders when its id matches active
- 6.App uses the composed API without passing props between subcomponents
your code
Hint
You need two levels of context: one global (which item is open) and one per item (what the id of this item is). That way Trigger and Panel know which item they belong to without receiving it as a prop.
Related concepts
Was this helpful?
Sign in to give feedback
