Children·续

export default function SeparatorList({ children }) { const result = []; Children.forEach(children, (child, index) => { result.push(child); result.push(<hr key={index} />); }); result.pop(); // Remove the last separator return result; }


> [!WARNING]
>
> As mentioned earlier, there is no way to get the rendered output of an inner component when manipulating `children`. This is why [it's usually better to use one of the alternative solutions.](#alternatives)
>

---

### Counting children

Call `Children.count(children)` to calculate the number of children.

```js
import RowList from './RowList.js';

export default function App() {
  return (
    &lt;RowList>
      &lt;p>This is the first item.&lt;/p>
      &lt;p>This is the second item.&lt;/p>
      &lt;p>This is the third item.&lt;/p>
    &lt;/RowList>
  );
}

```js src/RowList.js active import { Children } from 'react';

export default function RowList({ children }) { return ( <div className="RowList"> <h1 className="RowListHeader"> Total rows: {Children.count(children)} </h1> {Children.map(children, child => <div className="Row"> {child} </div> )} </div> ); }


```css
.RowList {
  display: flex;
  flex-direction: column;
  border: 2px solid grey;
  padding: 5px;
}

.RowListHeader {
  padding-top: 5px;
  font-size: 25px;
  font-weight: bold;
  text-align: center;
}

.Row {
  border: 2px dashed black;
  padding: 5px;
  margin: 5px;
}

[!WARNING]

As mentioned earlier, there is no way to get the rendered output of an inner component when manipulating children. This is why it's usually better to use one of the alternative solutions.


Converting children to an array

Call Children.toArray(children) to turn the children data structure into a regular JavaScript array. This lets you manipulate the array with built-in array methods like filter, sort, or reverse.

import ReversedList from './ReversedList.js';

export default function App() {
  return (
    &lt;ReversedList>
      &lt;p>This is the first item.&lt;/p>
      &lt;p>This is the second item.&lt;/p>
      &lt;p>This is the third item.&lt;/p>
    &lt;/ReversedList>
  );
}

```js src/ReversedList.js active import { Children } from 'react';

export default function ReversedList({ children }) { const result = Children.toArray(children); result.reverse(); return result; }


> [!WARNING]
>
> As mentioned earlier, there is no way to get the rendered output of an inner component when manipulating `children`. This is why [it's usually better to use one of the alternative solutions.](#alternatives)
>

---

## Alternatives

> [!NOTE]
>
> This section describes alternatives to the `Children` API (with capital `C`) that's imported like this:
>
```js
import { Children } from 'react';

Don't confuse it with using the children prop (lowercase c), which is good and encouraged.

Exposing multiple components

Manipulating children with the Children methods often leads to fragile code. When you pass children to a component in JSX, you don't usually expect the component to manipulate or transform the individual children.

When you can, try to avoid using the Children methods. For example, if you want every child of RowList to be wrapped in <div className="Row">, export a Row component, and manually wrap every row into it like this:

import { RowList, Row } from './RowList.js';

export default function App() {
  return (
    &lt;RowList>
      &lt;Row>
        &lt;p>This is the first item.&lt;/p>
      &lt;/Row>
      &lt;Row>
        &lt;p>This is the second item.&lt;/p>
      &lt;/Row>
      &lt;Row>
        &lt;p>This is the third item.&lt;/p>
      &lt;/Row>
    &lt;/RowList>
  );
}

```js src/RowList.js export function RowList({ children }) { return ( <div className="RowList"> {children} </div> ); }

export function Row({ children }) { return ( <div className="Row"> {children} </div> ); }


```css
.RowList {
  display: flex;
  flex-direction: column;
  border: 2px solid grey;
  padding: 5px;
}

.Row {
  border: 2px dashed black;
  padding: 5px;
  margin: 5px;
}

Unlike using Children.map, this approach does not wrap every child automatically. However, this approach has a significant benefit compared to the earlier example with Children.map because it works even if you keep extracting more components. For example, it still works if you extract your own MoreRows component:

import { RowList, Row } from './RowList.js';

export default function App() {
  return (
    &lt;RowList>
      &lt;Row>
        &lt;p>This is the first item.&lt;/p>
      &lt;/Row>
      &lt;MoreRows />
    &lt;/RowList>
  );
}

function MoreRows() {
  return (
    <>
      &lt;Row>
        &lt;p>This is the second item.&lt;/p>
      &lt;/Row>
      &lt;Row>
        &lt;p>This is the third item.&lt;/p>
      &lt;/Row>
    &lt;/>
  );
}

```js src/RowList.js export function RowList({ children }) { return ( <div className="RowList"> {children} </div> ); }

export function Row({ children }) { return ( <div className="Row"> {children} </div> ); }


```css
.RowList {
  display: flex;
  flex-direction: column;
  border: 2px solid grey;
  padding: 5px;
}

.Row {
  border: 2px dashed black;
  padding: 5px;
  margin: 5px;
}

This wouldn't work with Children.map because it would "see" <MoreRows /> as a single child (and a single row).


Accepting an array of objects as a prop

You can also explicitly pass an array as a prop. For example, this RowList accepts a rows array as a prop:

import { RowList, Row } from './RowList.js';

export default function App() {
  return (
    &lt;RowList rows={[
      { id: 'first', content: &lt;p>This is the first item.&lt;/p> },
      { id: 'second', content: &lt;p>This is the second item.&lt;/p> },
      { id: 'third', content: &lt;p>This is the third item.&lt;/p> }
    ]} />
  );
}

```js src/RowList.js export function RowList({ rows }) { return ( <div className="RowList"> {rows.map(row => ( <div className="Row" key={row.id}> {row.content} </div> ))} </div> ); }


```css
.RowList {
  display: flex;
  flex-direction: column;
  border: 2px solid grey;
  padding: 5px;
}

.Row {
  border: 2px dashed black;
  padding: 5px;
  margin: 5px;
}

Since rows is a regular JavaScript array, the RowList component can use built-in array methods like map on it.

This pattern is especially useful when you want to be able to pass more information as structured data together with children. In the below example, the TabSwitcher component receives an array of objects as the tabs prop:

import TabSwitcher from './TabSwitcher.js';

export default function App() {
  return (
    &lt;TabSwitcher tabs={[
      {
        id: 'first',
        header: 'First',
        content: &lt;p>This is the first item.&lt;/p>
      },
      {
        id: 'second',
        header: 'Second',
        content: &lt;p>This is the second item.&lt;/p>
      },
      {
        id: 'third',
        header: 'Third',
        content: &lt;p>This is the third item.&lt;/p>
      }
    ]} />
  );
}

```js src/TabSwitcher.js import { useState } from 'react';

export default function TabSwitcher({ tabs }) { const [selectedId, setSelectedId] = useState(tabs[0].id); const selectedTab = tabs.find(tab => tab.id === selectedId); return ( <> {tabs.map(tab => ( <button key={tab.id} onClick={() => setSelectedId(tab.id)} > {tab.header} </button> ))} <hr /> <div key={selectedId}> <h3>{selectedTab.header}</h3> {selectedTab.content} </div> </> ); }


Unlike passing the children as JSX, this approach lets you associate some extra data like `header` with each item. Because you are working with the `tabs` directly, and it is an array, you do not need the `Children` methods.

---

### Calling a render prop to customize rendering

Instead of producing JSX for every single item, you can also pass a function that returns JSX, and call that function when necessary. In this example, the `App` component passes a `renderContent` function to the `TabSwitcher` component. The `TabSwitcher` component calls `renderContent` only for the selected tab:

```js
import TabSwitcher from './TabSwitcher.js';

export default function App() {
  return (
    &lt;TabSwitcher
      tabIds={['first', 'second', 'third']}
      getHeader={tabId => {
        return tabId[0].toUpperCase() + tabId.slice(1);
      }}
      renderContent={tabId => {
        return &lt;p>This is the {tabId} item.&lt;/p>;
      }}
    />
  );
}

```js src/TabSwitcher.js import { useState } from 'react';

export default function TabSwitcher({ tabIds, getHeader, renderContent }) { const [selectedId, setSelectedId] = useState(tabIds[0]); return ( <> {tabIds.map((tabId) => ( <button key={tabId} onClick={() => setSelectedId(tabId)} > {getHeader(tabId)} </button> ))} <hr /> <div key={selectedId}> <h3>{getHeader(selectedId)}</h3> {renderContent(selectedId)} </div> </> ); }


A prop like `renderContent` is called a *render prop* because it is a prop that specifies how to render a piece of the user interface. However, there is nothing special about it: it is a regular prop which happens to be a function.

Render props are functions, so you can pass information to them. For example, this `RowList` component passes the `id` and the `index` of each row to the `renderRow` render prop, which uses `index` to highlight even rows:

```js
import { RowList, Row } from './RowList.js';

export default function App() {
  return (
    &lt;RowList
      rowIds={['first', 'second', 'third']}
      renderRow={(id, index) => {
        return (
          &lt;Row isHighlighted={index % 2 === 0}>
            &lt;p>This is the {id} item.&lt;/p>
          &lt;/Row>
        );
      }}
    />
  );
}

```js src/RowList.js import { Fragment } from 'react';

export function RowList({ rowIds, renderRow }) { return ( <div className="RowList"> <h1 className="RowListHeader"> Total rows: {rowIds.length} </h1> {rowIds.map((rowId, index) => <Fragment key={rowId}> {renderRow(rowId, index)} </Fragment> )} </div> ); }

export function Row({ children, isHighlighted }) { return ( <div className={[ 'Row', isHighlighted ? 'RowHighlighted' : '' ].join(' ')}> {children} </div> ); }


```css
.RowList {
  display: flex;
  flex-direction: column;
  border: 2px solid grey;
  padding: 5px;
}

.RowListHeader {
  padding-top: 5px;
  font-size: 25px;
  font-weight: bold;
  text-align: center;
}

.Row {
  border: 2px dashed black;
  padding: 5px;
  margin: 5px;
}

.RowHighlighted {
  background: #ffa;
}

This is another example of how parent and child components can cooperate without manipulating the children.


Troubleshooting

I pass a custom component, but the Children methods don't show its render result

Suppose you pass two children to RowList like this:

&lt;RowList>
  &lt;p>First item&lt;/p>
  &lt;MoreRows />
&lt;/RowList>

If you do Children.count(children) inside RowList, you will get 2. Even if MoreRows renders 10 different items, or if it returns null, Children.count(children) will still be 2. From the RowList's perspective, it only "sees" the JSX it has received. It does not "see" the internals of the MoreRows component.

The limitation makes it hard to extract a component. This is why alternatives are preferred to using Children.


Sitemap

Overview of all docs pages