Sub topic 6
Nesting content with the children prop
This chapter assumes you can write a function component, pass props as JSX attributes, and destructure props in a parameter list. It builds on those ideas to show how a component receives content from between its own tags.
What children is
Most props are attributes: <Avatar name="Grace" />. The children prop is different. React fills it with whatever you place between a component's opening and closing tags.
function Card({ title, children }) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}
export default function App() {
return (
<Card title="Profile">
<p>Software engineer</p>
</Card>
);
}Card never needs to know what it wraps. It decides the frame (a section with a heading), and the parent decides the content. This is how layouts, modals, panels, and buttons with icons are usually built.
children is an ordinary prop with a reserved meaning. These two lines produce the same result:
<Card title="Profile"><p>Software engineer</p></Card>
<Card title="Profile" children={<p>Software engineer</p>} />Use the nested form. Linters such as react/no-children-prop flag the attribute form because it hides the structure of the markup.
What can children contain
The value of children depends on what the parent wrote between the tags.
| Parent writes | Value of `children` |
|---|---|
| Nothing: `<Card />` or `<Card></Card>` | `undefined` |
| Text: `<Card>Hello</Card>` | The string `"Hello"` |
| One element | A single React element object |
| Several elements or expressions | An array of nodes |
| `{cond && <p>Hi</p>}` with `cond` false | `false` |
| `{list.map(...)}` | An array of elements |
| A function: `<Card>{() => ...}</Card>` | The function itself |
Two consequences follow. First, children can be a single element or an array depending on how many things the parent wrote, so don't index into it with children[0]. Second, values like false, null, and undefined render nothing, so {children} is always safe to place in JSX.
Whitespace and text
JSX trims whitespace at the start and end of lines inside a tag. This markup gives children the string "Hello world", with no leading or trailing spaces:
<Card title="Greeting">
Hello world
</Card>If you mix text and elements, you get an array such as ["Hello ", <b>world</b>]. React renders it correctly, but any code that expects a string will fail.
Defaults and conditional output
Because children is undefined when nothing is passed, you can supply fallback content. Use a default value in the destructuring, or branch on the value.
function Panel({ title, children }) {
return (
<section>
<h2>{title}</h2>
{children ?? <p>Nothing to show yet.</p>}
</section>
);
}
export default function App() {
return (
<>
<Panel title="Inbox" />
<Panel title="Notes">
<p>Buy milk</p>
</Panel>
</>
);
}Use ?? rather than || here. With ||, a child of 0 or an empty string is treated as missing and replaced by the fallback. With ??, only null and undefined trigger it. Note that false also passes through ?? and renders nothing, which is usually what you want.
Wrappers that add behavior
A common use is a wrapper that adds layout, styling, or behavior and leaves content to the caller. This example shows a collapsible section. The state lives inside the wrapper, and the children are rendered only when it is open.
import { useState } from 'react';
function Collapsible({ title, children }) {
const [open, setOpen] = useState(false);
return (
<div>
<button onClick={() => setOpen(!open)} aria-expanded={open}>
{title}
</button>
{open && <div>{children}</div>}
</div>
);
}
export default function App() {
return (
<Collapsible title="Shipping details">
<p>Orders ship within two business days.</p>
<p>Free returns for 30 days.</p>
</Collapsible>
);
}The children are elements created by App, so App owns them. When open changes, only Collapsible re-renders. React reuses the same children elements from the last render of App, which can skip work for the nested content. A later chapter covers this in more detail.
Working with a list of children
Sometimes you need to inspect or transform children, for example to add a separator between items. Do not treat props.children as an array, because it may be a single element or undefined. React provides Children helpers that handle every shape.
import { Children } from 'react';
function Stack({ children }) {
const items = Children.toArray(children);
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, removes null, undefined, and booleans, and assigns keys to each element. Here it yields two items, not three. Other helpers include Children.count, Children.map, and Children.only.
Treat these helpers as a last resort. They are fragile: Children.count does not count the contents of a fragment or a child component's output, only the nodes the parent passed. If you find yourself cloning children with cloneElement to inject props, prefer an explicit pattern such as named props or context, which the later composition chapter covers.
Functions as children
children can be any value, including a function. The wrapper then calls it and passes in data the parent could not otherwise reach. This is the render prop pattern in its simplest form.
import { useState } from 'react';
function Toggle({ children }) {
const [on, setOn] = useState(false);
return children({ on, toggle: () => setOn(!on) });
}
export default function App() {
return (
<Toggle>
{({ on, toggle }) => (
<button onClick={toggle}>{on ? 'On' : 'Off'}</button>
)}
</Toggle>
);
}React itself does not render a function, so only do this when the wrapper calls it. If a function child reaches {children} unchanged, React warns that functions are not valid as a React child.
Common errors
- Children are missing. A self-closing tag such as
<Card title="Profile" />passes no children. If the content was meant to show, check that the tag is not self-closed. - Children are not displayed. The component accepts
childrenbut never renders{children}. Nothing else shows the content. - Reading the wrong shape. Code like
children.map(...)throws "children.map is not a function" when the parent passes one element. UseChildren.maporChildren.toArray. - Expecting a string.
children.toUpperCase()works for<Label>hi</Label>but fails once someone adds an icon next to the text. If you need text, accept alabelstring prop instead. - Mutating children. Children are read-only like all props. Do not reassign or modify them. Create new elements if you need variants.
- Missing keys on mapped children. If the parent writes
{items.map(item => <li>{item}</li>)}withoutkey, React warns about keys. The wrapper cannot fix this, so addkeywhere the array is created. - Quoting an expression. Writing
<Card>{"<p>Hi</p>"}</Card>shows the literal text, not a paragraph. Put real JSX between the braces.
Children versus named props
Use children for the single main content area. When a component has several distinct areas, named props are clearer than guessing which child belongs where:
<Layout header={<h1>Dashboard</h1>} sidebar={<nav>Menu</nav>}>
<p>Main content</p>
</Layout>Here children is the main area, and header and sidebar are slots. This pairs the readability of nested markup with explicit placement. The next chapters in this tutorial cover slot props and render props in more depth.
Summary of rules
childrenholds whatever the parent placed between the tags, and it isundefinedwhen nothing was placed there.- Render it with
{children}anywhere inside the component. - Its shape varies: string, element, array, function, or nothing. Don't assume one shape.
- It is read-only. Wrapper components add structure around it and do not modify it.
- Use
Children.toArraywhen you must iterate, and prefer named props overcloneElementtricks.
Exercise
A teammate writes function List({ children }) { return <ul>{children.map(c => <li>{c}</li>)}</ul>; } and uses <List><span>One</span></List>. The page crashes. Why, and how do you fix it?
Show answer
With one child element, children is a single element object, not an array, so children.map is not a function. Use Children.map(children, c => <li>{c}</li>) or Children.toArray(children).map(...) after importing Children from 'react'. With toArray, add a key on each li, for example the index or c.key. Both approaches handle zero, one, or many children.
Exercise
You write function Banner({ children }) { return <div>{children || 'No message'}</div>; } and render <Banner>{count}</Banner> where count is 0. What appears, and what change gives the intended result?
Show answer
The fallback "No message" appears, because 0 is falsy and || replaces it. Use children ?? 'No message' so that only null and undefined trigger the fallback. Then 0 renders as the text "0".