Advanced React Patterns Advanced React Patterns

Flexible Compound Component & Exercise

Check out a free preview of the full Advanced React Patterns course:
The "Flexible Compound Component & Exercise" Lesson is part of the full, Advanced React Patterns course featured in this preview video. Here's what you'd learn in this lesson:

Showing the limitations of the basic compound components when needing additional nesting, Kent shows that the workaround is through leveraging context to share implicit state.

Get Unlimited Access Now

Transcript from the "Flexible Compound Component & Exercise" Lesson

[00:00:00]
>> Kent C. Dodds: Great, let's move on to our next exercise. So I'm gonna go ahead and reset, hard. Just get everything back in order, and we'll pull up exercise three. This is addressing a problem with compound components. So this usage looks almost the same, except there's a slight difference now.

[00:00:26] We have this div breaking up our perfect compound component structure. And if you run the app and go to the Flexible Compound Components and click here, you'll see that you can actually toggle the button. So why is that happening? Well, the button is toggled when it gets an on prop set to true and then an on prop set to false.

[00:00:48] And then it also caused the on toggle when it's passed the toggle function in on click. Well, it's not actually passed either of those things. And you'll actually see a warning that we saw similar with the span where we're passing a non-boolean attribute to our div. So what's happening is the React.Children.map function will only see the top level elements.

[00:01:21] It does'´t see any of the things that those things rendered. And so we're providing the right props to these two. But we're passing the props that are supposed to go to the switch to the button to this div. And so how do we solve this problem? Well, it used to be a little more complicated, but now it is really nice because we have the new context API.

[00:01:44] And we clearly obviously want to be on the latest, so you'll be using the new context API to solve this problem. It is gonna be a little bit of extra code for each one of our static components. Our compound components are gonna be using the context consumer. And at the top of the exercise, I give you kind of an example of how to use the context API.

[00:02:06] And you're gonna create your own toggle context, and then use the consumer inside of your static methods and then the producer inside of your render. So all this stuff is gonna go away and be replaced by toggle context provider. The tricky thing is the provider needs to also provide, as part of the value, this toggle function, so the button can operate and pull that out from the context.

[00:02:37] So I've given you a little tip here of what you're supposed to do. And maybe you can play around with it and figure out why you have to do that.