React
Beginner
1 min read
Passing and Receiving Props
Example
// Parent passes props; child reads them (read-only)
function ProductCard({ name, price, inStock, onAddToCart }) {
return (
<div style={{ border: '1px solid #ddd', padding: 16, borderRadius: 8 }}>
<h3>{name}</h3>
<p>Price: ${price.toFixed(2)}</p>
<p>
Availability:{' '}
<strong style={{ color: inStock ? 'green' : 'red' }}>
{inStock ? 'In Stock' : 'Out of Stock'}
</strong>
</p>
{/* Callback prop — child calls it, parent handles it */}
<button disabled={!inStock} onClick={() => onAddToCart(name)}>
Add to Cart
</button>
</div>
);
}
function Shop() {
const products = [
{ id: 1, name: 'Keyboard', price: 89.99, inStock: true },
{ id: 2, name: 'Monitor', price: 349.00, inStock: false },
];
const handleAdd = (name) => alert(`${name} added to cart`);
return (
<div>
{products.map(p => (
<ProductCard
key={p.id}
name={p.name}
price={p.price}
inStock={p.inStock}
onAddToCart={handleAdd}
/>
))}
</div>
);
}
export default Shop;