React ยท Chapter 22 of 42
Composition
React favors composition over inheritance for reusing code between components. Instead of extending a base component class, you build complex UIs by nesting and combining components.
A common composition technique is passing components as `children` or other props, allowing flexible, customizable component APIs.
Children prop
Any JSX nested inside a component's tags is available via `props.children`, letting you create wrapper/container components.
Slots via props
You can pass multiple pieces of JSX as different named props (like `header` and `footer`) for more complex layouts.
Example 1 (jsx)
function Card({ children }) {
return <div className="card">{children}</div>;
}
function App() {
return (
<Card>
<h2>Title</h2>
<p>Some content inside the card.</p>
</Card>
);
}Output
Title
Some content inside the card. (wrapped in a card div)Card renders whatever JSX is nested inside it via children.
Key points
- React favors composition over class inheritance.
- props.children lets components wrap arbitrary nested JSX.
- Composition enables flexible, reusable component APIs.
- Named JSX props can act as multiple 'slots' in a layout.
๐ก Note: Composition is one of React's most powerful patterns for building flexible design systems.
