Topic 8 of 54
Passing with Props
Overview
Components are great, but they are useless if they are completely static. 'Props' (short for properties) allow you to pass data from a parent component down to a child component. This makes your components dynamic and reusable. Think of props as arguments passed to a JavaScript function.
Syntax
Props flow downwards (unidirectional data flow) from parent to child. The child receives all attributes bundled into a single object called 'props'.
Passing and Receiving Props
jsx
// 1. The Child component receives a single 'props' object
function Greeting(props) {
return <h1>Hello, {props.name}! You are {props.age} years old.</h1>;
}
// 2. The Parent component passes the props down as attributes
function App() {
return (
<div>
{/* Passing strings, numbers, and booleans */}
<Greeting name="Alice" age={25} isStudent={true} />
<Greeting name="Bob" age={30} isStudent={false} />
</div>
);
}Common Pitfalls
- Trying to modify a prop (e.g., `props.name = 'New Name'`). This will cause errors and goes against React's core philosophy.
- Passing a number or boolean as a string (e.g., `age="25"` instead of `age={25}`).
Interview Tips
- A golden rule of React: Props are Read-Only (Immutable). A child component must NEVER attempt to modify its own props. If data needs to change, it must be State, not a Prop.
Real-World Example
A reusable Avatar component that accepts user data to display.
example
jsx
function UserAvatar(props) {
return (
<div className="avatar-wrapper">
<img src={props.imageUrl} alt={props.altText} width={props.size} />
{props.showBadge && <span className="online-badge"></span>}
</div>
);
}
function Profile() {
return (
<UserAvatar
imageUrl="/alice.jpg"
altText="Alice's profile"
size={100}
showBadge={true}
/>
);
}