Reactbeginner 7 min
Pass data into components so the same component can show different things.
How to pass values into a component with props and read them inside it.
A reusable component is only useful if you can customise it. Props are how a parent tells a child what to show.
Props (short for properties) are the inputs to a component. You pass them like HTML attributes, and the component receives them as an object.
It is common to destructure the object in the parameter list, which is shorter:
Strings go in quotes: name="Asha". Anything else (numbers, booleans, arrays) goes in curly braces: price={40}.
Props are read-only. A component must never change the props it receives. Data flows one way: from parent down to child.
Product destructures three props from its argument.App renders it twice with different values.{inStock ? "In stock" : "Sold out"} is a ternary: a compact if/else that works inside JSX.Add a third product and a new prop called color shown in the card.
props.name = "x".price="40" passes the text "40", not a number.undefined.{ } for non-strings.Next: state.
function Greeting({ name }) {
return <h2>Hello, {name}</h2>;
}function Greeting(props) {
return <h2>Hello, {props.name}</h2>;
}
<Greeting name="Asha" />function Product({ name, price, inStock }) {
return (
<div style={{ border: "1px solid #ccc", padding: 12, margin: "8px 0" }}>
<strong>{name}</strong> - {price} rupees
<div>{inStock ? "In stock" : "Sold out"}</div>
</div>
);
}
function App() {
return (
<div style={{ fontFamily: "system-ui" }}>
<Product name="Notebook" price={40} inStock={true} />
<Product name="Pen" price={10} inStock={false} />
</div>
);
}