React.Children Utilities and Types
You'll learn how to safely iterate and transform child elements using React's built-in utilities while respecting TypeScript's broad ReactNode type.
The Core Problem
When you receive children as a prop, TypeScript types it as ReactNode — which can be anything: a single element, an array, a string, null, or undefined. You can't just call .map() on it like an array. That's where React.Children utilities come in.
React.Children.map and forEach
These utilities handle the messy work of normalizing children into an iterable structure:
import React, { ReactNode } from 'react';
interface ListProps {
children: ReactNode;
}
function List({ children }: ListProps) {
// Safe: React.Children.map handles all ReactNode cases
return (
<ul>
{React.Children.map(children, (child, index) => (
<li key={index}>{child}</li>
))}
</ul>
);
}
// Works with single child, multiple, or fragments
<List><span>One</span></List>
<List><span>One</span><span>Two</span></List>
Type Safety
The callback receives each child typed as ReactNode. React.Children.map returns ReactNode[] (or undefined if no children). React.Children.forEach returns void for side effects only.
React.Children.forEach(children, (child) => {
// child is ReactNode - could be element, string, number, etc.
console.log(child);
});
Think of It Like This
React.Children.map is like a Swiss Army knife for the children prop — it automatically handles single items, arrays, fragments, and edge cases that raw .map() would choke on.
Key Takeaway: Use React.Children.map/forEach when you need to iterate over children — they safely handle the broad ReactNode type and normalize all the different shapes children can take.