Compose instead of configure
So far you passed data to a component with regular props (title,
name...). But often what you want to pass is not a piece of data, but another
chunk of UI: what you write between the opening and closing tags of the
component.
React delivers that content through a special prop: children.
function Card({ children }) {
return <div className="card">{children}</div>;
}
And it is used by wrapping any markup:
<Card>
<h2>Hello</h2>
<p>I'm the content of the card.</p>
</Card>
Here Card doesn't know nor care what's inside: it just wraps it with a
border, some padding or a shadow. That makes it a reusable container
component: the same Card works for text, a form or an image.
Why it's so useful
- Real reuse: the "frame" (style, layout) lives in one place; the content is decided by whoever uses the component.
- Fewer props: instead of inventing
titleText,bodyText,imageUrl... you let the caller compose the interior freely.
function Layout({ children }) {
return (
<main className="layout">
<header>My App</header>
<section>{children}</section>
</main>
);
}
function App() {
return (
<Layout>
<h1>Home page</h1>
</Layout>
);
}
childrencan be a single element, several, text, or evennull. React treats it like any other prop: you render it with{children}wherever you want.