function Welcome({ name }) {
return <h2>Welcome, {name}</h2>;
}
function App() {
return <Welcome name="Ravi" />;
}<Welcome name="Ravi" />: passes a prop callednamewith the value"Ravi"function Welcome({ name }): React always passes exactly one argument โ a single props object โ and{ name }destructures it directly in the function parameters
function ProductCard({ title, price, inStock, tags }) {
return (
<div>
<h3>{title}</h3>
<p>โน{price}</p>
<p>{inStock ? "In Stock" : "Sold Out"}</p>
</div>
);
}
<ProductCard
title="Wireless Mouse"
price={799}
inStock={true}
tags={["electronics", "sale"]}
/>Props can be strings, numbers, booleans, arrays, objects, or even functions โ anything JavaScript can hold. Note that non-string values (numbers, booleans, objects) must be wrapped in curly braces.
function Card({ children }) {
return <div className="card">{children}</div>;
}
<Card>
<h3>Anything goes here</h3>
<p>This is the children prop.</p>
</Card>
// Default values
function Welcome({ name = "Guest" }) {
return <h2>Welcome, {name}</h2>;
}children is a special, automatically-provided prop containing whatever JSX was nested between a component's opening and closing tags โ it's what makes wrapper components like modals and cards possible.
Props are strictly read-only โ writing name = "New Value" inside a component that received name as a prop either does nothing or throws an error. If a value needs to change over time, it belongs in state (Chapter 12), not props.
Create a UserCard component accepting name, role, and an optional isOnline prop with a default value of false, and render it twice with different data.
function UserCard({ name, role, isOnline = false }) {
return (
<div>
<h3>{name}</h3>
<p>{role}</p>
<p>{isOnline ? "๐ข Online" : "โซ Offline"}</p>
</div>
);
}
function App() {
return (
<>
<UserCard name="Meera" role="Designer" isOnline={true} />
<UserCard name="Dev" role="Developer" />
</>
);
}
Q Can I pass a function as a prop?
Yes โ this is extremely common, especially for event handlers passed from parent to child, and is covered fully in Chapter 17 (Child-to-Parent Communication).
Q What happens if I don't pass a required prop?
The component receives undefined for that prop and tries to render it as such, usually resulting in missing or blank content rather than a crash. Using default values or TypeScript (in later, more advanced projects) helps catch this earlier.