Props
Pass data into components to make them flexible and truly reusable.
What you will learn
- Pass props to a component
- Read props (with destructuring)
- Build configurable components
Props = inputs to a component
Props (properties) let you pass data into a component, like attributes on an HTML tag. The component reads them to customise what it shows.
function Greeting(props) {
return <h3>Hello, {props.name}!</h3>;
}
function App() {
return (
<div>
<Greeting name="Asha" />
<Greeting name="Ravi" />
<Greeting name="Meera" />
</div>
);
}The Greeting component receives a props object and reads props.name inside its heading. In App we use it three times, each with a different name attribute: name="Asha", name="Ravi", name="Meera". Those attributes become the props for each copy, so the same component prints three different greetings. Props are how you pass data into a component, just like passing arguments to a function.
Note: Output:
Hello, Asha!
Hello, Ravi!
Hello, Meera!
One Greeting definition produced three different lines — only the name prop changed.
Destructure for cleaner code
It is common to destructure props right in the parameter list.
function ProductCard({ name, price }) {
return (
<div style={{ border: "1px solid #e6e8f0", borderRadius: 10, padding: 12, margin: 6 }}>
<h4>{name}</h4>
<p>₹{price}</p>
</div>
);
}
function App() {
return (
<div>
<ProductCard name="Keyboard" price={1200} />
<ProductCard name="Mouse" price={600} />
</div>
);
}This time we wrote function ProductCard({ name, price }) — the { name, price } in the parentheses pulls those two values straight out of props, so inside we can write {name} and {price} directly instead of props.name and props.price. In App we pass them as attributes: name="Keyboard" price={1200}. Notice price={1200} uses braces because 1200 is a number; name="Keyboard" uses quotes because it is text.
Note: Output: Two bordered cards: Keyboard — ₹1200 Mouse — ₹600
Watch out: Props are read-only. A component must never change its own props. To handle data that changes over time, use state — the next unit.
Q. What are props used for?
✍️ Practice
- Build a
Greetingcomponent that takes anameprop and use it three times. - Build a
ProductCardwithnameandpriceprops.
🏠 Homework
- Build a
UserCardthat takesname,roleandcityprops and render several users.