The React.Children Utilities
What you'll learn: How to safely work with the children prop using React's built-in helper methods.
Why These Utilities Exist
You've been passing children to components and rendering them directly. But what if you need to count how many children you received, or transform each child, or convert children to an array? The children prop can be a single element, an array, or even null—and that inconsistency makes it tricky to work with directly.
React provides React.Children utilities to handle these cases safely.
The Four Core Methods
React.Children.map(children, fn) — Like Array.map, but works whether children is one element or many:
function AddClass({ children }) {
return React.Children.map(children, child =>
<div className="wrapper">{child}</div>
);
}
React.Children.forEach(children, fn) — Iterates without returning a new array (for side effects only).
React.Children.count(children) — Returns the number of children, even if it's just one element:
function List({ children }) {
const count = React.Children.count(children);
return <div>Showing {count} items</div>;
}
React.Children.toArray(children) — Converts children to a flat array, useful before sorting or filtering:
const childArray = React.Children.toArray(children);
const sorted = childArray.sort(/* ... */);
When You Need Them
Use these when building wrapper components that need to inspect or transform their children—like tabs, carousels, or layout grids that add styling around each child element.
Key Takeaway: React.Children utilities let you safely iterate, count, and transform the children prop regardless of whether it's one element, many, or none.