In this exercise, we learned how to obtain all the children of a component at once using
this.props.children. However, is there a way to obtain or work with the individual children of a component?
Yes, React provides a helpful API for working with a component’s children through
React.Children. Some of the helpful functionality it provides are as follows:
You can turn the data structure returned by
this.props.children into a flat array with keys assigned to each child, using
React.Children.toArray(). This is one of the common methods to be able to access each individual child of the component.
You can also map a function on each individual child using
And, you can also get the number of children of the component using
In addition to these, there are a few other useful methods provided by
React.Children, which you can check out in the official documentation.