Course contentsShow
← React
Lesson 1085 of 2,39628. Composition: Compound ComponentsFree lesson

Building a Menu Component

Creating Menu, Menu.Button, Menu.Items, and Menu.Item with implicit open/close state.

Building a Menu Component

You'll learn how to create a compound Menu component with implicit open/close state shared between its children.

The Core Idea

A Menu component is a perfect candidate for the compound component pattern. You want a <Menu> parent that manages whether the menu is open or closed, a <Menu.Button> that toggles it, a <Menu.Items> container for the dropdown, and individual <Menu.Item> components for each option. The beauty? None of the children need explicit isOpen or onClick props—they communicate implicitly through the parent.

Building the Structure

Your Menu parent holds the open/close state internally. Menu.Button automatically knows to toggle that state when clicked. Menu.Items automatically knows whether to render based on that state. Menu.Item components can handle their own click logic while the parent decides when to close.

Think of it like a restaurant kitchen: the head chef (Menu) controls whether orders are being taken. The order window (Menu.Button) signals when to open or close. The prep stations (Menu.Items) only operate when open. Individual dishes (Menu.Item) are prepared according to their own recipes, but the kitchen's state governs everything.

The Pattern in Action

<Menu>
  <Menu.Button>Options</Menu.Button>
  <Menu.Items>
    <Menu.Item onClick={handleEdit}>Edit</Menu.Item>
    <Menu.Item onClick={handleDelete}>Delete</Menu.Item>
  </Menu.Items>
</Menu>

Notice: no isOpen prop drilling, no onToggle callbacks passed around. The compound structure handles it all internally.

Key Takeaway: A Menu compound component encapsulates open/close state in the parent and implicitly shares it with Menu.Button, Menu.Items, and Menu.Item children, creating a clean API without prop drilling.