React
Beginner
1 min read
Component Composition and the Children Prop
Example
// Generic Card container — accepts any children
function Card({ title, children, footer }) {
return (
<div style={{ border: '1px solid #ccc', borderRadius: 8, padding: 16, margin: 8 }}>
{title && <h3 style={{ marginTop: 0 }}>{title}</h3>}
<div>{children}</div>
{footer && <div style={{ borderTop: '1px solid #eee', marginTop: 8, paddingTop: 8 }}>{footer}</div>}
</div>
);
}
// Alert component — wraps children in a styled box
function Alert({ type = 'info', children }) {
const colors = { info: '#dbeafe', success: '#dcfce7', error: '#fee2e2' };
return (
<div style={{ background: colors[type], padding: '10px 16px', borderRadius: 6 }}>
{children}
</div>
);
}
// Composing everything together
function App() {
return (
<Card
title="User Profile"
footer={<button>Edit Profile</button>}
>
<Alert type="success">
<strong>Welcome back!</strong> Your profile is complete.
</Alert>
<p>Name: Alice</p>
<p>Email: alice@example.com</p>
</Card>
);
}
export default App;