React Children

React.Children provides utilities for dealing with the this.props.children data structure.

Child Component

Child is a JavaScript expression inside a parent. Children in React don't have to be components, they can be anything. You can pass any JavaScript expression as children, including functions, arrays, object, etc.

Parents can decide not to render any children or to manipulate them before rendering. A parent can access its children from props.children and because can have one element, multiple elements, or none at all, this value is a single child node, an array of child nodes or undefined.

A React Child has the following key properties:

$$typeof
Used by React to verify the child is a valid element.
key
A special string attribute you need to set when creating lists.
props
The props being passed down to the child.
ref
The ref function assigned to the child in order to be accessible outside of the typical dataflow.
type
A function used to create the component or a string.

API overview

map(children, function)
Similar to Array.prototype.map. Invokes a function on every immediate child and returns an array. If children is null or undefined returns null.
forEach(children, function)
Similar to Array.prototype.forEach. Invokes a function on every immediate child and returns nothing.
count(children)
Returns the total number of components in children.
only(children)
Verifies that children has only one child and returns it, otherwise throws error.
toArray(children)
Returns the children data structure as a flat array wth keys assigned to each child.

Looping over children

import React from "react";

class MyComponent extends React.Component {
  // component implementation

  render() {
    return (
      <div>
        {// Ignore the first child
        React.Children.map(this.props.children, (child, i) => {
          if (i < 1) return null;
          return child;
        })}
      </div>
    );
  }
}

Counting children

import React from "react";

class MyComponent extends React.Component {
  // component implementation

  render() {
    return (
      <div>
        {`This component has ${React.Children.count(
          this.props.children
        )} children.`}
      </div>
    );
  }
}

Enforcing single child

import React from "react";

class MyComponent extends React.Component {
  // component implementation

  render() {
    try {
      const child = React.Children.only(this.props.children);
      return <div>{child}</div>;
    } catch (err) {
      return null;
    }
  }
}

Immutably cloning elements

import React from "react";

class MyComponent extends React.Component {
  // component implementation

  render() {
    return (
      <div>
        {React.Children.map(this.props.children, (child, i) => {
          return React.cloneElement(child, {
            // Change the initial properties of the child
          });
        })}
      </div>
    );
  }
}

Back to API