Component Composition
Composition lets you build complex UIs by combining small, reusable pieces.
The children Prop
Every component receives children — the content between its tags:
function Card({ children }) {
return <div className="card">{children}</div>;
}
<Card>
<h2>Title</h2>
<p>Content goes here.</p>
</Card>
Layout Components
Wrap shared structure in layout components:
function PageLayout({ children }) {
return (
<div className="layout">
<header>Nav</header>
<main>{children}</main>
<footer>Footer</footer>
</div>
);
}
<PageLayout>
<h1>Home</h1>
</PageLayout>
Slot Pattern
Pass specific pieces as named props:
function Modal({ title, body, footer }) {
return (
<div className="modal">
<h2>{title}</h2>
<div>{body}</div>
<div>{footer}</div>
</div>
);
}
<Modal
title="Confirm"
body={<p>Are you sure?</p>}
footer={<button>OK</button>}
/>
Extracting Reusable Layouts
Combine composition with props for flexible patterns:
function Sidebar({ children, side = "left" }) {
return (
<aside className={`sidebar sidebar-${side}`}>
{children}
</aside>
);
}
Best Practices
- Favor composition over inheritance
- Use
childrenfor generic wrappers - Use named props for specific slots
- Keep layout components simple and presentational
Common Mistakes
- Nesting too many layers makes debugging hard
- Passing everything as
childrenloses clarity - Forgetting to spread props when needed