Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Write Compound Components


    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 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/>.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: 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.

    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.

    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.

    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.

    Now they need access to the state of the toggle and even the toggle click handler, so let's go ahead and return 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.

    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.

    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.

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