Components & Props
Components are the building blocks of every React application. Props (short for properties) are how parent components pass data down to child components — they are read-only.
1 Function Components
React — Function Component
// A simple component — just a function that returns JSX
function Button({ label, onClick, variant = "primary" }) {
return (
<button
className={`btn btn-${variant}`}
onClick={onClick}
>
{label}
</button>
);
}
// Usage
function App() {
return (
<>
<Button label="Save" onClick={() => alert("Saved!")} />
<Button label="Cancel" variant="secondary" onClick={() => {}} />
</>
);
}
2 Props Patterns
React — Props Patterns
// Default props via destructuring
function Avatar({ src, alt = "User", size = 48 }) {
return (
<img
src={src}
alt={alt}
style={{ width: size, height: size, borderRadius: "50%" }}
/>
);
}
// Spread props
function Input({ className, ...rest }) {
return <input className={`input ${className}`} {...rest} />;
}
// children prop — compose components
function Card({ title, children }) {
return (
<div className="card">
<h2 className="card-title">{title}</h2>
<div className="card-body">{children}</div>
</div>
);
}
// Usage
<Card title="My Post">
<p>Any JSX can go here as children.</p>
<Button label="Read More" />
</Card>
3 Component Composition
React — Composing Components
function ProductCard({ product }) {
return (
<Card title={product.name}>
<Avatar src={product.image} alt={product.name} size={80} />
<p>${product.price}</p>
<Button label="Add to Cart" onClick={() => addToCart(product)} />
</Card>
);
}
function ProductList({ products }) {
return (
<div className="grid">
{products.map(p => (
<ProductCard key={p.id} product={p} />
))}
</div>
);
}
4 Code Challenge
Challenge: Build a
StatCard component that takes title, value, icon, and trend ("+12%" or "-3%") props. Render the trend in green if positive and red if negative.