Answer
A compound component is a type of component that manages the internal state of a feature while delegating control of the rendering to the place of implementation opposed to the point of declaration. They provide a way to shield feature specific logic from the rest of the app providing a clean and expressive API for consuming the component.
Internally they are built to operate on a set of data that is passed in through children instead of props. Behind the scenes they make use of React's lower level API such as React.children.map()
, and React.cloneElement()
. Using these methods, the component is able to express itself in such a way that promotes patterns of composition and extensibility.
Example:
function App() {
return (
<Menu>
<MenuButton>
Actions <span aria-hidden>▾</span>
</MenuButton>
<MenuList>
<MenuItem onSelect={() => alert('Download')}>Download</MenuItem>
<MenuItem onSelect={() => alert('Copy')}>Create a Copy</MenuItem>
<MenuItem onSelect={() => alert('Delete')}>Delete</MenuItem>
</MenuList>
</Menu>
)
}
In this example, the <Menu>
establishes some shared implicit state. The <MenuButton>
, <MenuList>
, and <MenuItem>
components each access and/or manipulate that state, and it's all done implicitly. This allows you to have the expressive API you're looking for.