Write Compound Components

Kent C. Dodds
InstructorKent C. Dodds
Share this video with your friends

Social Share Links

Send Tweet

Compound components give more rendering control to the user. The functionality of the component stays intact while how it looks and the order of the children can be changed at will. We get this functionality by using the special React.Children.map function to map over the children given to our <Toggle/> component. We map over the children to pass the on state as a prop to its children. We move the visual pieces of the component out into function components and add them as static properties to <Toggle/>.

Instructor: [00:00] In this usage example, we have this toggle component and then we have this three compound components that implicitly access the state of the toggle component and even a state updater like the toggle function.

[00:12] Let's start by creating a static on component that will accept an on and children. If it's on, it will render children. Otherwise, it will render no.

[00:23] We'll have a very similar off component, which will render no or children, and then we'll have a static button component which will accept on and toggle, and then it will just take the rest of the props.

[00:36] That will render a switch with on as on and onClick is toggle, and then spread the rest of the props. Those are the compound components.

[00:45] Now they need access to the state of the toggle and even the toggle click handler, so let's go ahead and return React.Children.map(this.props.children) and for each of these child elements, we'll return a React.cloneElement of the child element. We'll provide additional props like on from state and toggle from this.toggle.

[01:11] With that, things are functioning perfectly. It allows users to render things however they like, without us having to provide some sort of render configuration prop as an additional API for users to learn.

[01:24] In review, to make this possible we created a couple of static compound components -- on, off, and button -- which each accesses the toggle state and click handler that they needed, and receive those as props implicitly in the render method of the toggle.

[01:39] Now users of our component can render this however they like, and that state will be shared with these compound components implicitly.