Skip to main content

Children

Utilities for manipulating and transforming the children 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

The Children implementation in Preact:

Key Features

  1. Null Handling: Safely handles null or undefined children
  2. Flattening: Uses toChildArray from Preact core to flatten nested arrays
  3. Context Binding: Supports binding a context object for map and forEach
  4. Validation: only throws 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 the Children API in Preact:

Direct Array Methods

Array.isArray Check

Direct Render

With TypeScript

Type the children parameter:

Performance Considerations

  1. Overhead: Children methods add overhead - avoid if not needed
  2. Direct Arrays: Use array methods directly when possible
  3. Keys: Always provide keys when using Children.map
  4. Immutability: Children.map creates new arrays - be mindful in hot paths

Best Practices

  1. Prefer Direct Rendering: Use {children} directly when possible
  2. Type Safety: Use TypeScript for better type checking
  3. Keys: Always provide keys when mapping children
  4. Validation: Use Children.only for components expecting single children
  5. Error Handling: Handle the case when Children.only throws

Comparison with React

Preact’s Children API is compatible with React’s, but simpler:
  • No Children.map context 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 Children API

Source

Implementation: compat/src/Children.js:1-22