Children
[!WARNING]
Using
Childrenis uncommon and can lead to fragile code. See common alternatives.
Children lets you manipulate and transform the JSX you received as the children prop.
const mappedChildren = Children.map(children, child =>
<div className="Row">
{child}
</div>
);
Reference
Children.count(children)
Call Children.count(children) to count the number of children in the children data structure.
```js src/RowList.js active import { Children } from 'react';
function RowList({ children }) { return ( <>
Total rows: {Children.count(children)}
... </> ); }
[See more examples below.](#counting-children)
#### Parameters
* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component.
#### Returns
The number of nodes inside these `children`.
#### Caveats
- Empty nodes (`null`, `undefined`, and Booleans), strings, numbers, and [React elements](/reference/react/createElement) count as individual nodes. Arrays don't count as individual nodes, but their children do. **The traversal does not go deeper than React elements:** they don't get rendered, and their children aren't traversed. [Fragments](/reference/react/Fragment) don't get traversed.
---
### `Children.forEach(children, fn, thisArg?)`
Call `Children.forEach(children, fn, thisArg?)` to run some code for each child in the `children` data structure.
```js src/RowList.js active
import { Children } from 'react';
function SeparatorList({ children }) {
const result = [];
Children.forEach(children, (child, index) => {
result.push(child);
result.push(<hr key={index} />);
});
// ...
Parameters
children: The value of thechildrenprop received by your component.fn: The function you want to run for each child, similar to the arrayforEachmethod callback. It will be called with the child as the first argument and its index as the second argument. The index starts at0and increments on each call.- optional
thisArg: Thethisvalue with which thefnfunction should be called. If omitted, it'sundefined.
Returns
Children.forEach returns undefined.
Caveats
- Empty nodes (
null,undefined, and Booleans), strings, numbers, and React elements count as individual nodes. Arrays don't count as individual nodes, but their children do. The traversal does not go deeper than React elements: they don't get rendered, and their children aren't traversed. Fragments don't get traversed.
Children.map(children, fn, thisArg?)
Call Children.map(children, fn, thisArg?) to map or transform each child in the children data structure.
```js src/RowList.js active import { Children } from 'react';
function RowList({ children }) { return (
[See more examples below.](#transforming-children)
#### Parameters
* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component.
* `fn`: The mapping function, similar to the [array `map` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) callback. It will be called with the child as the first argument and its index as the second argument. The index starts at `0` and increments on each call. You need to return a React node from this function. This may be an empty node (`null`, `undefined`, or a Boolean), a string, a number, a React element, or an array of other React nodes.
* **optional** `thisArg`: The [`this` value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) with which the `fn` function should be called. If omitted, it's `undefined`.
#### Returns
If `children` is `null` or `undefined`, returns the same value.
Otherwise, returns a flat array consisting of the nodes you've returned from the `fn` function. The returned array will contain all nodes you returned except for `null` and `undefined`.
#### Caveats
- Empty nodes (`null`, `undefined`, and Booleans), strings, numbers, and [React elements](/reference/react/createElement) count as individual nodes. Arrays don't count as individual nodes, but their children do. **The traversal does not go deeper than React elements:** they don't get rendered, and their children aren't traversed. [Fragments](/reference/react/Fragment) don't get traversed.
- If you return an element or an array of elements with keys from `fn`, **the returned elements' keys will be automatically combined with the key of the corresponding original item from `children`.** When you return multiple elements from `fn` in an array, their keys only need to be unique locally amongst each other.
---
### `Children.only(children)`
Call `Children.only(children)` to assert that `children` represent a single React element.
```js
function Box({ children }) {
const element = Children.only(children);
// ...
Parameters
children: The value of thechildrenprop received by your component.
Returns
If children is a valid element, returns that element.
Otherwise, throws an error.
Caveats
- This method always throws if you pass an array (such as the return value of
Children.map) aschildren. In other words, it enforces thatchildrenis a single React element, not that it's an array with a single element.
Children.toArray(children)
Call Children.toArray(children) to create an array out of the children data structure.
```js src/ReversedList.js active import { Children } from 'react';
export default function ReversedList({ children }) { const result = Children.toArray(children); result.reverse(); // ...
#### Parameters
* `children`: The value of the [`children` prop](/learn/passing-props-to-a-component#passing-jsx-as-children) received by your component.
#### Returns
Returns a flat array of elements in `children`.
#### Caveats
- Empty nodes (`null`, `undefined`, and Booleans) will be omitted in the returned array. **The returned elements' keys will be calculated from the original elements' keys and their level of nesting and position.** This ensures that flattening the array does not introduce changes in behavior.
---
## Usage
### Transforming children
To transform the children JSX that your component [receives as the `children` prop,](/learn/passing-props-to-a-component#passing-jsx-as-children) call `Children.map`:
```js {6,10}
import { Children } from 'react';
function RowList({ children }) {
return (
<div className="RowList">
{Children.map(children, child =>
<div className="Row">
{child}
</div>
)}
</div>
);
}
In the example above, the RowList wraps every child it receives into a <div className="Row"> container. For example, let's say the parent component passes three <p> tags as the children prop to RowList:
<RowList>
<p>This is the first item.</p>
<p>This is the second item.</p>
<p>This is the third item.</p>
</RowList>
Then, with the RowList implementation above, the final rendered result will look like this:
<div className="RowList">
<div className="Row">
<p>This is the first item.</p>
</div>
<div className="Row">
<p>This is the second item.</p>
</div>
<div className="Row">
<p>This is the third item.</p>
</div>
</div>
Children.map is similar to to transforming arrays with map(). The difference is that the children data structure is considered opaque. This means that even if it's sometimes an array, you should not assume it's an array or any other particular data type. This is why you should use Children.map if you need to transform it.
import RowList from './RowList.js';
export default function App() {
return (
<RowList>
<p>This is the first item.</p>
<p>This is the second item.</p>
<p>This is the third item.</p>
</RowList>
);
}
```js src/RowList.js active import { Children } from 'react';
export default function RowList({ children }) { return (
```css
.RowList {
display: flex;
flex-direction: column;
border: 2px solid grey;
padding: 5px;
}
.Row {
border: 2px dashed black;
padding: 5px;
margin: 5px;
}
[!INFO]
Why is the children prop not always an array?
In React, the
childrenprop is considered an opaque data structure. This means that you shouldn't rely on how it is structured. To transform, filter, or count children, you should use theChildrenmethods.In practice, the
childrendata structure is often represented as an array internally. However, if there is only a single child, then React won't create an extra array since this would lead to unnecessary memory overhead. As long as you use theChildrenmethods instead of directly introspecting thechildrenprop, your code will not break even if React changes how the data structure is actually implemented.Even when
childrenis an array,Children.maphas useful special behavior. For example,Children.mapcombines the keys on the returned elements with the keys on thechildrenyou've passed to it. This ensures the original JSX children don't "lose" keys even if they get wrapped like in the example above.[!WARNING]
The
childrendata structure does not include rendered output of the components you pass as JSX. In the example below, thechildrenreceived by theRowListonly contains two items rather than three:
<p>This is the first item.</p><MoreRows />This is why only two row wrappers are generated in this example:
import RowList from './RowList.js';
export default function App() {
return (
<RowList>
<p>This is the first item.</p>
<MoreRows />
</RowList>
);
}
function MoreRows() {
return (
<>
<p>This is the second item.</p>
<p>This is the third item.</p>
</>
);
}
```js src/RowList.js import { Children } from 'react';
export default function RowList({ children }) { return (
```css
.RowList {
display: flex;
flex-direction: column;
border: 2px solid grey;
padding: 5px;
}
.Row {
border: 2px dashed black;
padding: 5px;
margin: 5px;
}
There is no way to get the rendered output of an inner component like
<MoreRows />when manipulatingchildren. This is why it's usually better to use one of the alternative solutions.
Running some code for each child
Call Children.forEach to iterate over each child in the children data structure. It does not return any value and is similar to the array forEach method. You can use it to run custom logic like constructing your own array.
import SeparatorList from './SeparatorList.js';
export default function App() {
return (
<SeparatorList>
<p>This is the first item.</p>
<p>This is the second item.</p>
<p>This is the third item.</p>
</SeparatorList>
);
}
```js src/SeparatorList.js active import { Children } from 'react';
