Is there a way to work with the individual children of a component?

Question

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.

13 Likes

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()?

1 Like

simplest use would be

List.js

export class List extends React.Component {
  render() {
    let titleText = `Favorite ${this.props.type}`;
    if (React.Children.count(this.props.children) > 1) {
    	titleText += 's';
    }
    return (
      <div>
        <h1>{titleText}</h1>
        <ul>
            {this.props.children}
        </ul>
      </div>
    );
  }
}
8 Likes

Here is official React API for React.Children. Feel free to bookmark this for future use.