Sub topic 8
Nesting content with children
This chapter covers the children prop: how a component receives the content nested between its tags, what values that content can take, and where this pattern stops working well. It assumes you can write a function component, destructure props, and read basic JSX. The earlier chapters on props and on what JSX compiles to cover that background.
Content between tags becomes a prop
A component can render content that its caller supplies. Anything placed between a component's opening and closing tags arrives as a prop named children.
function Card({ title, children }) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}
export default function App() {
return (
<Card title="Welcome">
<p>This paragraph is passed as children.</p>
</Card>
);
}Card decides the surrounding structure: a section, a class name, and a heading. App decides what goes inside. Card does not need to know whether the content is a paragraph, a form, or another Card.
The {children} expression is a normal JSX expression, like any other value in curly braces. If you forget it, the nested content is accepted by React and then silently never displayed. This is the most common children bug.
What children actually is
children is an ordinary property on the props object. React gives it a different shape depending on what the caller wrote.
| Caller writes | Value of `children` |
|---|---|
| `<Card />` | `undefined` |
| `<Card>text</Card>` | the string `"text"` |
| `<Card>{42}</Card>` | the number `42` |
| `<Card><p>Hi</p></Card>` | one React element |
| `<Card><p>A</p><p>B</p></Card>` | an array of two elements |
| `<Card>{items.map(...)}</Card>` | an array |
| `<Card>{false}</Card>` | `false` |
Because the shape varies, avoid code that assumes a fixed type. Calling children.map(...) throws when there is a single child, because a single element is not an array. Calling children.length is wrong for the same reason.
For most components this does not matter. You place {children} in the output and React renders whatever it receives. Values that are null, undefined, true, and false render nothing. Strings and numbers render as text. Arrays render each item in order.
What the compiler produces
The children prop is not special syntax. The JSX compiler writes it into the props object for you. With the automatic JSX runtime, the usage from the previous example compiles roughly to this:
import { jsx as _jsx } from 'react/jsx-runtime';
function Card({ title, children }) {
return _jsx('section', {
className: 'card',
children: [_jsx('h2', { children: title }), children],
});
}
const element = _jsx(Card, {
title: 'Welcome',
children: _jsx('p', { children: 'This paragraph is passed as children.' }),
});Real compiler output differs slightly. For example, it uses a variant called jsxs when an element has several static children. The point is that nested content and attributes end up in the same object. This also explains two behaviors:
- Writing
<Card children={<p>Hi</p>} />is equivalent to nesting the paragraph. Linters usually flag it as bad style. - If you pass both an explicit
childrenattribute and nested content, the nested content wins. Avoid doing both.
How JSX handles whitespace in children
When the children are text, JSX applies fixed whitespace rules:
- Whitespace at the start and end of a line is removed.
- Blank lines are removed.
- Text spread across several lines is joined with a single space.
- Whitespace between an element and text on the same line is kept.
function Note({ children }) {
return <p className="note">{children}</p>;
}
export default function App() {
return (
<Note>
Save your work
before leaving.
</Note>
);
}This renders Save your work before leaving. with one space and no leading or trailing space. If you need a space at a line boundary next to an element, write it as {' '}.
Composition: wrappers and layouts
The children prop is the basis for wrapper components. Layouts, panels, modals, and list containers all use it.
function Panel({ heading, children }) {
return (
<aside className="panel">
<h3>{heading}</h3>
<div className="panel-body">{children}</div>
</aside>
);
}
function UserSummary({ user }) {
return (
<Panel heading={user.name}>
<p>{user.email}</p>
<p>Joined {user.joined}</p>
</Panel>
);
}
export default function App() {
const user = { name: 'Ada', email: '[email protected]', joined: '2024' };
return (
<Panel heading="Account">
<UserSummary user={user} />
</Panel>
);
}Here a Panel contains a UserSummary, which itself renders a Panel. Each wrapper only controls its own frame. Content flows downward through nested children, as the diagram shows.
Several slots: use named props
A single children prop gives one insertion point. If a layout needs several regions, you can pass JSX through ordinary props, since a prop can hold any value, including elements.
function PageLayout({ header, sidebar, children }) {
return (
<div className="page">
<header>{header}</header>
<nav>{sidebar}</nav>
<main>{children}</main>
</div>
);
}
export default function App() {
return (
<PageLayout
header={<h1>Dashboard</h1>}
sidebar={<a href="/settings">Settings</a>}
>
<p>Main content goes here.</p>
</PageLayout>
);
}Use children for the main body and named props for the other regions. This is clearer than inspecting the children to work out which part is which.
Children that are functions
Because children can be any value, a caller can pass a function. The wrapper calls it with data it owns. This is sometimes called a render prop.
import { useState } from 'react';
function Toggle({ children }) {
const [on, setOn] = useState(false);
return (
<div>
<button onClick={() => setOn(!on)}>Switch</button>
{children(on)}
</div>
);
}
export default function App() {
return <Toggle>{(on) => <p>The light is {on ? 'on' : 'off'}.</p>}</Toggle>;
}This works, but a function as children is unusual. Most code that needs this today uses a custom hook or a dedicated prop name such as render. Know the pattern so you can read it, and do not reach for it by default.
Inspecting and transforming children
Sometimes a wrapper needs to count or reshape what it receives. React provides Children utilities for this, because the shape of children varies.
import { Children } from 'react';
function Stack({ children }) {
const items = Children.toArray(children);
if (items.length === 0) {
return <p>No items.</p>;
}
return (
<ul>
{items.map((child, index) => (
<li key={index}>{child}</li>
))}
</ul>
);
}
export default function App() {
return (
<Stack>
<span>One</span>
{false}
<span>Two</span>
</Stack>
);
}Children.toArray always returns a flat array, drops empty values such as false, null, and undefined, and assigns keys to elements. This renders two list items, not three.
Know the limits of these tools:
- A fragment counts as a single child.
Childrendoes not look inside it, so<><A /><B /></>is one item. - A component that renders other elements internally is also opaque. You see the
<Row />element, not whatRowreturns. - Index keys are fine here because the list is not reordered. See the lists and keys chapter for when they are not.
The React documentation lists structure-sensitive uses of Children as fragile for these reasons. Prefer explicit props, or let the caller wrap each item themselves.
Edge cases and common errors
- Forgetting
{children}. The wrapper renders its frame and nothing inside it. - Assuming an array. Use
Children.toArrayif you must iterate. Do not call array methods directly onchildren. - Mutating
children. Props are read-only. To change an element, create a modified copy or restructure the data, and do not assign to its properties. - Treating
0as empty.{count && <Badge />}renders0whencountis0. This applies to children too, since a number child is displayed as text. - Expecting a wrapper to re-render its children on its own state change. Elements passed as
childrenare created by the parent. When the wrapper's own state changes, React can reuse those same elements. This is often useful for performance, but it surprises people who expect the nested content to be rebuilt. - Passing
childrento a self-closing tag.<Card />giveschildrenthe valueundefined. Make sure the wrapper can render without content, or give it a fallback.
A fallback can be written inline:
function Empty({ children }) {
return <div>{children ?? 'Nothing here yet.'}</div>;
}The ?? operator only falls back for null or undefined, so an explicit 0 or an empty string still renders as given.
Exercise
A component Box({ children }) returns <div className="box"></div>. A teammate writes <Box><p>Hello</p></Box> and sees an empty box. What is wrong, and what would you change so that it also shows No content when no children are supplied?
Show answer
The component never renders children, so React accepts the nested paragraph and discards it. Change the body to <div className="box">{children ?? 'No content'}</div>. Using ?? shows the fallback for undefined (and null) but still renders other values such as 0.
Exercise
A wrapper calls children.map(...). It works for <List><Item /><Item /></List> but throws for <List><Item /></List>. Why, and how do you fix it?
Show answer
With two or more nested elements children is an array, but with one it is a single element, which has no map method. Wrap the access in Children.toArray(children) (imported from react), which always returns an array, or avoid iterating and render {children} directly.