पाठ 5 / 25
Children and Composition
Build flexible components by nesting.
Pass UI, not just data
Anything between a component's opening and closing tags arrives as the special children prop. This enables composition: a Card, Modal or Layout component provides structure and lets the caller decide the content. You can also pass elements in named props (header={<Title />}). Composition usually beats inheritance and long lists of configuration props, and it can also avoid passing data through many layers.
Composition with children and slots
Not run here; a common pattern.
function Card({ title, actions, children }) {
return (
<section className="card">
<header><h3>{title}</h3>{actions}</header>
<div className="card-body">{children}</div>
</section>
);
}
<Card title="Invoice #1042" actions={<button>Pay</button>}>
<p>Due on 12 October</p>
<InvoiceLines id={1042} />
</Card>Prefer children over many flags
Instead of props like showFooter, footerText, footerAlign, accept a footer element and let callers compose it.
त्वरित जाँच: What is the children prop?
- A list of child processes
- The content nested between a component's opening and closing tags
- Only text strings
- The component's state
Answer
The content nested between a component's opening and closing tags — Composition through children.