Capítulo 77 de 116

Chapter 77: Children

Core Idea

The Children utility (Children.map, .forEach, .count, .only, .toArray) provides array-like operations over the children prop — necessary because children isn't guaranteed to be a plain array (it can be a single element, a string, or nested fragments), so calling regular array methods on it directly isn't safe.

Key Concepts

  • Why not just .map() on children directly: props.children can be a single child, null, a string, or an arbitrarily nested structure — not reliably an array — so Children.map(children, fn) normalizes over all of those shapes the way Array.prototype.map would for an actual array.
  • Children.map(children, fn) transforms each child, similar to Array.map, handling null/nested structures correctly and preserving key uniqueness.
  • Children.count(children) returns the number of children, correctly counting through nested structures.
  • Children.only(children) asserts there's exactly one child and returns it, throwing if there isn't — used when a component's contract requires a single child element.
  • Children.toArray(children) flattens children into a real, flat array — each element additionally gets a unique key derived from its position, useful when a component needs to actually reorder or otherwise array-manipulate its children.
  • The docs frame Children as increasingly a legacy/uncommon pattern. Composing with explicit named props (passing specific elements as distinct props, e.g. <Layout header={<Header/>} content={<Content/>} />) is generally the more explicit, more maintainable alternative to manipulating an opaque children prop — reach for Children mainly when a component's contract genuinely is "wrap an arbitrary list of children."

Code Examples

function List({ children }) {
  return (
    <ul>
      {Children.map(children, (child, i) => <li key={i}>{child}</li>)}
    </ul>
  );
}
  • What it demonstrates: safely mapping over children regardless of whether it's a single element or several, wrapping each in an <li>.

Key Takeaways

  1. Never assume children is a plain array — use Children utilities (or restructure to explicit named props) instead of raw Array.prototype methods on it.
  2. Children.only is a useful assertion for enforcing a "single child" component contract, failing loudly otherwise.
  3. Consider whether explicit named props would make a component's API clearer before reaching for generic children manipulation — the docs lean toward that being the more modern, explicit pattern.

Connects To

  • Ch 15 (Passing Props to a Component): the children prop mechanism these utilities operate on.
  • Ch 67 (Fragment): a common source of nested structure within children that these utilities normalize over.