React Composition & children
React favours composition over inheritance: instead of building special subclasses of components, you build general components and plug other components into them. The main tool for this is the special children prop.
The children prop
Whatever you put between a component's opening and closing tags arrives in its children prop:
function Card({ title, children }) {
return (
<div style={{ border: '1px solid #ddd', borderRadius: 10, padding: 14, marginBottom: 10, width: 300, boxShadow: '0 2px 6px #0001' }}>
<h3 style={{ marginTop: 0 }}>{title}</h3>
{children}
</div>
);
}
export default function App() {
return (
<div>
<Card title="Weather">
<p style={{ fontSize: 30, margin: 0 }}>☀️ 31°C</p>
<p>Sunny all afternoon in Da Nang.</p>
</Card>
<Card title="Reminder">
<ul>
<li>Buy coffee beans</li>
<li>Call the dentist</li>
</ul>
</Card>
</div>
);
}Card doesn't know or care what it contains. It provides the frame; the parent decides the content.
Wrapper components
Layouts, dialogs, panels and buttons are natural wrappers. Children can be text, elements, other components, or a mix:
import { useState } from 'react';
function Button({ variant = 'primary', children, ...rest }) {
const colors = { primary: '#1677ff', danger: '#e5484d', neutral: '#888' };
return (
<button
{...rest}
style={{ background: colors[variant], color: 'white', border: 'none', padding: '8px 14px', borderRadius: 6, marginRight: 6, cursor: 'pointer' }}
>
{children}
</button>
);
}
function Dialog({ title, children, actions }) {
return (
<div style={{ border: '1px solid #ccc', borderRadius: 10, width: 320, overflow: 'hidden' }}>
<div style={{ background: '#f2f2f2', padding: '8px 12px', fontWeight: 'bold' }}>{title}</div>
<div style={{ padding: 12 }}>{children}</div>
<div style={{ padding: 12, borderTop: '1px solid #eee', textAlign: 'right' }}>{actions}</div>
</div>
);
}
export default function App() {
const [status, setStatus] = useState('File not deleted yet.');
return (
<div>
<Dialog
title="Delete file?"
actions={
<>
<Button variant="neutral" onClick={() => setStatus('Cancelled.')}>Cancel</Button>
<Button variant="danger" onClick={() => setStatus('report.pdf deleted 🗑️')}>Delete</Button>
</>
}
>
<p><strong>report.pdf</strong> will be permanently removed.</p>
</Dialog>
<p>{status}</p>
</div>
);
}Two techniques appear here:
- Multiple "slots": besides
children, any prop can receive JSX —actionsfills the footer slot. - Rest props:
...restcollects the remaining props (onClick,disabled,type, …) and{...rest}forwards them to the real<button>.
Specialization
A specific component can be built by configuring a general one — no inheritance required:
function Alert({ icon, color, title, children }) {
return (
<div style={{ borderLeft: `5px solid ${color}`, background: `${color}18`, padding: '8px 12px', margin: '8px 0', width: 340 }}>
<strong>{icon} {title}</strong>
<div>{children}</div>
</div>
);
}
function SuccessAlert({ children }) {
return <Alert icon="✅" color="#2e7d32" title="Success">{children}</Alert>;
}
function WarningAlert({ children }) {
return <Alert icon="⚠️" color="#ed6c02" title="Warning">{children}</Alert>;
}
export default function App() {
return (
<div>
<SuccessAlert>Your profile was saved.</SuccessAlert>
<WarningAlert>Your trial ends in 3 days.</WarningAlert>
<Alert icon="💡" color="#0288d1" title="Did you know?">Composition beats inheritance.</Alert>
</div>
);
}Avoiding prop drilling with composition
When a deeply nested component needs data, beginners often pass props through many layers that don't use them ("prop drilling"). Often you can avoid this by passing the finished element down instead:
import { useState } from 'react';
function Layout({ sidebar, children }) {
return (
<div style={{ display: 'flex', gap: 12 }}>
<aside style={{ width: 140, background: '#f5f5f5', padding: 8 }}>{sidebar}</aside>
<main>{children}</main>
</div>
);
}
function UserBadge({ user }) {
return <div>👤 {user.name}<br /><small>{user.role}</small></div>;
}
export default function App() {
const [user, setUser] = useState({ name: 'Nhi', role: 'Editor' });
return (
<Layout sidebar={<UserBadge user={user} />}>
<h3>Dashboard</h3>
<button onClick={() => setUser({ ...user, role: user.role === 'Editor' ? 'Admin' : 'Editor' })}>
Toggle role
</button>
</Layout>
);
}Layout never sees user — it simply places the elements it receives. App owns the data and composes the pieces.
Render props
Sometimes a wrapper must give data back to its content. Then pass a function as a child or prop, and the wrapper calls it:
function MouseTracker({ render }) {
const [pos, setPos] = useState({ x: 0, y: 0 });
return (
<div onMouseMove={(e) => setPos({ x: e.clientX, y: e.clientY })} style={{ height: 120 }}>
{render(pos)}
</div>
);
}
<MouseTracker render={(pos) => <p>Mouse at {pos.x}, {pos.y}</p>} />Today, custom hooks cover most of what render props were used for, but you will still meet the pattern in libraries.
Patterns at a glance
| Pattern | Looks like | Use for |
|---|---|---|
children |
<Card>…</Card> |
generic containers |
| Named slots | <Dialog actions={…}> |
several content areas |
| Specialization | <SuccessAlert> wraps <Alert> |
preconfigured variants |
| Rest props | {...rest} |
forwarding HTML attributes |
| Render prop | render={(data) => …} |
wrapper provides data to content |
Test yourself
In <Card><p>Hi</p></Card>, how does Card access the paragraph?
- props.content
- props.children
- this.inner
- useChildren()
What does {...rest} on a <button> do in a wrapper component?
- Copies the button
- Forwards the remaining props such as onClick to the button
- Resets the styles
- Removes all props
How does React recommend building a SuccessAlert from a general Alert?
- class SuccessAlert extends Alert
- Render <Alert> with preset props inside SuccessAlert
- Copy and paste Alert's code
- Use a mixin