Props β Passing Data to Components
After completing this topic, you will:
Understand how props work, the role of children, and what prop drilling is.
What are Props?
Just like you can add attributes to HTML tags, you can also pass data to React components:
<UserCard name="Alice" age={25} />These name and age are props (properties). They are a way for a parent component to pass data to its child component.
Receiving Props
function UserCard({ name, age }) {
return (
<div>
<h2>{name}</h2>
<p>{age} years old</p>
</div>
);
}Use destructuring to extract only the necessary props. You can also receive the entire props object:
function UserCard(props) {
return <h2>{props.name}</h2>;
}Props are Read-Only
function UserCard({ name }) {
name = "Bob"; // This works, but you shouldn't do it
return <h2>{name}</h2>;
}In React, props should be treated as read-only. If a child component modifies the data passed by the parent, it can lead to confusing data flow.
If you need to change the value, manage the state in the parent and pass down a function to update it:
function Parent() {
const [name, setName] = useState("Alice");
return <Child name={name} onNameChange={setName} />;
}
function Child({ name, onNameChange }) {
return <input value={name} onChange={e => onNameChange(e.target.value)} />;
}Default Values
You can set default values for props that are not passed:
function Button({ label = "Click", size = "medium" }) {
return <button className={size}>{label}</button>;
}
<Button /> // label="Click", size="medium"
<Button label="Save" /> // label="Save", size="medium"Children β A Special Prop
Content placed between tags is passed as the children prop:
function Card({ children }) {
return <div className="card">{children}</div>;
}
<Card>
<h2>Title</h2>
<p>Content</p>
</Card>This is useful for creating layout components. You can reuse the wrapping structure while changing only the content inside.
Prop Drilling
<App> β user
<Layout> β user
<Sidebar> β user
<Avatar> β user.name - only used hereProp drilling is when data is passed through intermediate components. In this case, the intermediate components (Layout, Sidebar) don't use the user prop, but they still need to pass it down.
While 2-3 levels deep is acceptable, consider using Context or a state management library if it goes deeper.
Key Takeaways
Props are a way for the parent to pass data to the child, and they are read-only.
childrenis a special prop that passes the content between tags. Prop drilling can occur when data is passed too deeply.