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?
Answer
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 React.Children.forEach().
And, you can also get the number of children of the component using React.Children.count().
In addition to these, there are a few other useful methods provided by React.Children, which you can check out in the official documentation.
It is really helpful to know that we can work with individual children of a component in different ways. However, I can’t seem to get this to work in the exercise. Can you provide an example of using React.Children.count()?
For this assignment
if (this.props.children instanceof Array) {
titleText += ‘s’;
}
is the reason why the output is pluralized or not. My question is where is “Array” coming from? Or is a
automatically considered a array when more than one list item is in it?
If a component has more than one child between its JSX tags, then this.props.children will return those children in an array. However, if a component has only one child, then this.props.children will return the single child, *not* wrapped in an array.t
Hi, I am impressed with the way to convert props.children to an array.
However, since we know that when a component has more than one child between its JSX tags, children are returned in an array. Also, when there is only one child between the JSX tag, the child is not wrapped in an array. Then can I say that we use the method React.Children.toArray() to wrap the child/children because we can’t predict the number of children in between JSX tags and we need an array to perform indexing or slicing? Then if we know for sure that there is more than one child between the JSX tag, we don’t need to call React.Children.toArray(), right? Thanks in advance.