Runnable lesson · press Try it on the examples to edit and run them here.
So far each component showed the same thing every time. Props (short for properties) let a parent give a component different data, so one component can show many different things.
An everyday analogy
A function becomes useful when it takes arguments: add(2, 3) and add(10, 20) use the same code with different input. Props are the arguments of a component.
Passing and reading a prop
You pass a prop like an HTML attribute. The component receives all props as one object, usually its first parameter:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return <Welcome name="Ada" />;
}
<Welcome name="Ada" /> creates the props object { name: "Ada" } and passes it to Welcome. Inside, props.name is "Ada".
One component, many outputs
Now Welcome is reusable, because every use can pass something different:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return (
<div>
<Welcome name="Ada" />
<Welcome name="Grace" />
<Welcome name="Linus" />
</div>
);
}
Props can hold any value
Strings go in quotes. Everything else goes in braces: numbers, booleans, arrays, objects, functions and even JSX. Passing Props shows all of them.
function Person(props) {
return <p>{props.name} is {props.age}</p>;
}
function App() {
return <Person name="Ada" age={36} />;
}
The data flow rule
Props travel in one direction: from parent to child. A child cannot change its own props, and it cannot reach up and change the parent’s variables. When a child needs to tell the parent something, the parent passes a function as a prop and the child calls it. Passing Functions as Props shows how. This one-way flow is what makes React apps predictable: if a value is wrong, you only need to look up the tree.
Props change what is shown
When a parent re-renders with new prop values, the child re-renders too, and shows the new data. You never update props yourself.
function PriceTag(props) {
return <p>Price: ${props.value}</p>;
}
function App() {
const [price, setPrice] = React.useState(10);
return (
<div>
<PriceTag value={price} />
<button onClick={() => setPrice(price + 5)}>Raise price</button>
</div>
);
}
The price is state in App. PriceTag receives it as a prop. State belongs to one component; props carry it down. Props vs State compares them.
Key points
- Props are the inputs of a component: an object passed as its first argument.
- Pass strings in quotes and every other value in braces.
- Data flows down from parent to child; a child never modifies its props.