Our current compound component implementation is great, but it's limited in that users cannot render the structure they need. Let's allow the user to have more flexibility by using React context to share the implicit state to our child <Toggle/>
components. We will walk through using React's official context API with React.createContext
and use the given Provider
and Consumer
components to share state implicitly between our compound components giving our users the flexibility they need out of our component.
Instructor: [00:00] Our toggle button is now broken, and it's because somebody's using our compound components in an unexpected way, by nesting the toggle button in a div.
[00:08] The problem is that we're mapping over our this.props.children, but that only includes toggle on, toggle off, and a div. It doesn't include any of the children of those child elements.
[00:21] If we want to enable this kind of structural flexibility, then we need to find some other way to provide the on and toggle properties to these components. We're going to use React Context to do that.
[00:35] We'll start with consttogglecontext=react.createcontext. Then we'll use toggle context provider to provide these values to our compound components.
[00:45] We'll return toggle context provider. As the children, it'll be this.props.children. For the value, we'll actually provide the same object here. Then we can remove this.
[00:59] Next we need to update our compound components to consume those values rather than accept them as props, so we'll start with this one. We'll take this, and we'll return togglecontext.consumer.
[01:12] As the children here, it's going to be a function that accepts the context value and returns what we want it to render, so we'll say contextvalue.on.
[01:22] Now we no longer need the on prop because the on component is going to be responsible for getting that context value out of context using the toggle context consumer.
[01:32] We'll do something very similar for the off static component. We'll get rid of this one. We'll change this to off, and if it is on, then we'll render null. Otherwise, we'll render children.
[01:44] For the button, we'll render togglecontext.consumer. For children, we'll say context value and render the switch, where on comes from contextvalue.on, and toggle comes from contextvalue.toggle.
[02:03] Then we don't need on and toggle from props anymore. We can just call this props, and spread the rest of the props to the switch. With that, our toggle button is now working again.