Compound components allow you to create and use components that share state. React.Children provides many methods for rendering child components efficiently.
- [Instructor] Compound components allow you to create and use components that share a state. Let's go ahead and take our now eating and menu components out of here and instead we're going to render this display component. The display component is going to display something based on a truthy or falsy variable, so let's do this, we're gonna say if truthy is true, we'll set that default argument there, and then finally we will pass in children.
The next step is we're going to use another one of those in line if else, we're gonna check to see if truthy is true, now if it is, then we're going to call this function react.children.only so what this is gonna do is it's going to make sure that children only has one child and then it's going to return it, the other option is just to return null, so if there are no children then we'll return null.
We'll also setup here a value for h, let's go ahead and set that to 18, and we're also going to use if truthy, we're gonna pass down this property so we'll say, age is greater than or equal to, 18, so our display component we're gonna want to render some sort of a child here, so let's go ahead and render an h1, this h1 should say you can vote, that's US rules there, now if this is true, if this evaluates as true, we're gonna go ahead and display this, if not then we won't render anything.
So let's give that a save, we're gonna look at it in the browser, and we're gonna see that we can indeed vote. What if we changed this value to say 12. We're gonna see nothing. So this is an example of using a compound component where sharing some state information between the display component and any children, so this h1 particular. If you're interested in learning more about react.children or other ways to manipulate elements with react APIs, just check out the docs and you'll be able to see all of the methods that are available on react.children.
Here's the one that we used react.children.only.
- What's new in React 16
- Rendering arrays
- Controlled, uncontrolled, and compound components
- Using keyed fragments
- Working with new lifecycle methods
- React patterns
- Using the context API
- Checking for accessibility issues in your React code