Components
Function components, composition, the children prop, and component design
Skills taught: react.function-components, react.composition, react.children-prop, react.component-design
Composing components
// Small, focused components compose into larger UIs
function Avatar({ name, size = 40 }) {
const initials = name.split(' ').map(w => w[0]).join('');
return (
<div style={{
width: size, height: size,
borderRadius: '50%',
background: '#4fd1c5',
display: 'flex', alignItems: 'center', justifyContent: 'center',
color: '#0e1116', fontWeight: 'bold', fontSize: size * 0.4
}}>
{initials}
</div>
);
}
function UserCard({ name, role, bio }) {
return (
<div style={{ display: 'flex', gap: '12px', padding: '12px', border: '1px solid #e2e8f0', borderRadius: '8px' }}>
<Avatar name={name} size={48} />
<div>
<h3 style={{ margin: '0 0 4px' }}>{name}</h3>
<p style={{ margin: '0 0 4px', color: '#6b7280', fontSize: '0.85rem' }}>{role}</p>
<p style={{ margin: 0, fontSize: '0.9rem' }}>{bio}</p>
</div>
</div>
);
}
function App() {
return (
<div style={{ fontFamily: 'sans-serif', padding: '8px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
<h2>Team</h2>
<UserCard name="Alice Singh" role="Frontend Engineer" bio="React enthusiast" />
<UserCard name="Bob Sharma" role="Backend Developer" bio="Loves databases" />
</div>
);
}
The children prop
// children is whatever is between the component's open and close tags
function Card({ title, children, accent = '#4fd1c5' }) {
return (
<div style={{
border: `2px solid ${accent}`,
borderRadius: '8px',
overflow: 'hidden',
marginBottom: '8px'
}}>
<div style={{ background: accent, padding: '8px 12px' }}>
<strong style={{ color: '#0e1116' }}>{title}</strong>
</div>
<div style={{ padding: '12px' }}>
{children} {/* ← renders whatever is placed between <Card> and </Card> */}
</div>
</div>
);
}
function App() {
return (
<div style={{ fontFamily: 'sans-serif', padding: '8px', maxWidth: '400px' }}>
<Card title="React Facts">
<p>React uses a virtual DOM for fast updates.</p>
<p>Components are just functions!</p>
</Card>
<Card title="Important" accent="#f87171">
<ul>
<li>Component names start with capital letters</li>
<li>JSX must have one root element</li>
</ul>
</Card>
</div>
);
}
Frequently Asked Questions
How do I know when to extract a new component?
Three signals: (1) Repetition — if you copy-paste the same JSX block twice, make it a component. (2) Complexity — if a JSX block is too long to scan at a glance, extract it. (3) Reuse — if the same UI pattern appears in different contexts. Start with fewer components and extract as complexity grows, rather than pre-splitting everything upfront.