Capítulo 77 de 116
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.
.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.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."function List({ children }) {
return (
<ul>
{Children.map(children, (child, i) => <li key={i}>{child}</li>)}
</ul>
);
}
children regardless of whether it's a single element or several, wrapping each in an <li>.children is a plain array — use Children utilities (or restructure to explicit named props) instead of raw Array.prototype methods on it.Children.only is a useful assertion for enforcing a "single child" component contract, failing loudly otherwise.children manipulation — the docs lean toward that being the more modern, explicit pattern.children prop mechanism these utilities operate on.children that these utilities normalize over.