React — Props
What are Props?
Props (short for properties) are used to pass data from parent to child components. They are read-only.
Basic Props
function Welcome({ name, age }) {
return (
<div>
<h1>Hello, {name}!</h1>
<p>You are {age} years old.</p>
</div>
);
}
// Usage
<Welcome name="John" age={25} />
Props as Objects
function UserCard({ user }) {
return (
<div className="card">
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
);
}
// Usage
<UserCard user={{ name: "John", email: "john@example.com" }} />
Children Props
function Card({ title, children }) {
return (
<div className="card">
<h3>{title}</h3>
<div className="card-body">
{children}
</div>
</div>
);
}
// Usage
<Card title="My Card">
<p>This is the card content.</p>
</Card>
Default Props
function Button({ text = "Click me", variant = "primary" }) {
return (
<button className={`btn btn-${variant}`}>
{text}
</button>
);
}
// Usage
<Button /> // text="Click me", variant="primary"
<Button text="Submit" variant="success" />
Props Examples
// Product card
function ProductCard({ product }) {
return (
<div className="product-card">
<img src={product.image} alt={product.name} />
<h3>{product.name}</h3>
<p>${product.price}</p>
<button>Add to Cart</button>
</div>
);
}
// User list
function UserList({ users }) {
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
// Usage
function App() {
const products = [
{ id: 1, name: "Laptop", price: 999, image: "laptop.jpg" },
{ id: 2, name: "Phone", price: 699, image: "phone.jpg" }
];
return (
<div>
{products.map(product => (
<ProductCard key={product.id} product={product} />
))}
</div>
);
}
Mini Practice
Write React code that:
- Passes props to a component
- Uses children props
- Sets default prop values
- Passes arrays and objects as props
Up Next
Next: Learn about State.
Related Topics
Frequently Asked Questions about Props
What is Props in React?
Props is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Props?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Props.
Why is Props important in React?
Props is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.