Children
Utilities for manipulating and transforming thechildren prop. This API is mostly unnecessary in Preact but provided for React compatibility.
API
Methods
Children.map
Transform each child and return a new array.Children.forEach
Iterate over children without returning anything.Children.count
Count the number of children.Children.only
Verify that children contains only one child and return it. Throws an error if there are multiple children.Children.toArray
Convert children to a flat array of VNodes.Implementation Details
TheChildren implementation in Preact:
Key Features
- Null Handling: Safely handles
nullorundefinedchildren - Flattening: Uses
toChildArrayfrom Preact core to flatten nested arrays - Context Binding: Supports binding a context object for
mapandforEach - Validation:
onlythrows an error if multiple children are present
Common Use Cases
Adding Props to All Children
Filtering Children
Conditional Rendering
Wrapping Each Child
When NOT to Use Children
In most cases, you don’t need theChildren API in Preact:
Direct Array Methods
Array.isArray Check
Direct Render
With TypeScript
Type the children parameter:Performance Considerations
- Overhead:
Childrenmethods add overhead - avoid if not needed - Direct Arrays: Use array methods directly when possible
- Keys: Always provide keys when using
Children.map - Immutability:
Children.mapcreates new arrays - be mindful in hot paths
Best Practices
- Prefer Direct Rendering: Use
{children}directly when possible - Type Safety: Use TypeScript for better type checking
- Keys: Always provide keys when mapping children
- Validation: Use
Children.onlyfor components expecting single children - Error Handling: Handle the case when
Children.onlythrows
Comparison with React
Preact’sChildren API is compatible with React’s, but simpler:
- No
Children.mapcontext parameter in Preact: The third parameter is supported but rarely used - Simpler implementation: Built on top of Preact’s
toChildArray - Full compatibility: Works with React code expecting the
ChildrenAPI