React.Children API provides utilities for working with the props.children data structure. These methods handle the complexity of children being a single element, an array, or other data types.
In modern React, you can often use regular JavaScript array methods by converting children to an array with
Children.toArray() first, or use the methods directly.Children.map()
Invoke a function on every immediate child and return an array of results.ReactNode
required
The
props.children value passed to your component. Can be:- A single React element
- An array of elements
- A string, number, or other renderable value
null,undefined, orfalse- Nested arrays or fragments
function
required
The function to call for each child. It receives:
child- The current child elementindex- The index of the child in the flat list
null/undefined to exclude it.any
Optional context value to use as
this when calling the function.null/undefined if children was null/undefined.
Usage
Basic mapping:Key Handling
Children.map() automatically handles keys for you:
- Keys are automatically assigned to returned elements
- If the original child has a key, it’s preserved and used as part of the new key
- You don’t need to manually add keys to the returned elements
Flattening
Children.map() automatically flattens nested structures:
Children.forEach()
Iterate over children without returning an array.ReactNode
required
The children to iterate over.
function
required
Function to call for each child. Receives
child and index as arguments.any
Optional
this context for the function.undefined
Usage
Children.count()
Return the number of children.ReactNode
required
The children to count.
Usage
Children.toArray()
Convert children to a flat array with keys assigned.ReactNode
required
The children to convert to an array.
children is null or undefined.
Usage
Basic conversion:Key Assignment
Children.toArray() automatically assigns keys to elements that don’t have them:
Children.only()
Assert that children contains exactly one child and return it.ReactNode
required
The children value to validate.
Error if children is not a single React element.
Usage
When to Use Children.only()
Use when:- Your component can only work with a single child element
- You need to call
cloneElementon the child - You want to enforce API constraints at runtime
- Your component can handle multiple children
- You just want the first child (use
Children.toArray(children)[0]instead) - You want to allow text or other non-element children
Common Patterns
Wrapping Each Child
Conditional Rendering Based on Children
Grouping Children
Performance Consideration:While
Children utilities are convenient, they do add some overhead. For performance-critical code with large numbers of children, consider alternative patterns like render props or passing arrays directly as props instead of using props.children.