Sub topic 7
Passing data with props
This chapter assumes you can write a function component that returns JSX and that you know JavaScript destructuring, default parameter values, and the spread operator. You should also know how curly braces embed expressions in JSX. Here you will learn how a parent component gives data to a child, what the child receives, and which mistakes come up most often.
What props are
Props (short for properties) are the inputs to a component. A parent sets them as attributes on the child's JSX tag. React collects all of those attributes into one plain object and passes that object to the child function as its first argument.
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
export default function App() {
return <Greeting name="Ada" />;
}React calls Greeting({ name: 'Ada' }). The tag <Greeting name="Ada" /> is the call site, and the attributes are the argument.
Data moves in one direction only: from parent to child. A child cannot assign new values to the props it received. If a child needs to ask the parent to change something, the parent passes down a function, as described below.
Receiving props with destructuring
Most code destructures the props object in the parameter list. This documents which props the component uses and removes the props. prefix.
function UserBadge({ name, role }) {
return (
<p>
{name} ({role})
</p>
);
}
export default function App() {
return <UserBadge name="Ada" role="admin" />;
}Destructuring pulls out only the names you list. Props that the parent passes but you do not list are still in the object, but your code never reads them.
Passing values of different types
An attribute written with quotes is always a string. An attribute written with curly braces holds any JavaScript expression: a number, boolean, array, object, function, or the result of a calculation.
function Product({ name, price, tags, inStock, onBuy }) {
return (
<section>
<h2>{name}</h2>
<p>Price: ${price.toFixed(2)}</p>
<p>Tags: {tags.join(', ')}</p>
<p>{inStock ? 'In stock' : 'Sold out'}</p>
<button onClick={onBuy} disabled={!inStock}>
Buy
</button>
</section>
);
}
export default function App() {
return (
<Product
name="Keyboard"
price={49.5}
tags={['usb', 'mechanical']}
inStock={true}
onBuy={() => console.log('Buying')}
/>
);
}The table below lists the forms you will use most.
| You write | The child receives |
|---|---|
| `count="3"` | The string `"3"` |
| `count={3}` | The number `3` |
| `visible={true}` | The boolean `true` |
| `visible` | The boolean `true` (shorthand) |
| `user={{ name: 'Ada' }}` | An object (outer braces are JSX, inner braces are the object literal) |
| `onSave={handleSave}` | A function reference |
Passing a function as a prop is the standard way for a child to notify its parent. The child calls the function, and the parent's code runs. This works because functions are ordinary values in JavaScript.
import { useState } from 'react';
function LikeButton({ onLike }) {
return <button onClick={onLike}>Like</button>;
}
export default function App() {
const [likes, setLikes] = useState(0);
return (
<>
<LikeButton onLike={() => setLikes(likes + 1)} />
<p>{likes} likes</p>
</>
);
}Here the state lives in App. LikeButton only knows that it was given a function to call.
Default values
Give a prop a default with a default value in the destructuring pattern.
function Button({ label = 'Submit', size = 'medium' }) {
return <button className={`btn btn-${size}`}>{label}</button>;
}
export default function App() {
return (
<>
<Button />
<Button label="Cancel" size="small" />
</>
);
}This matters when a parent computes a value that may be missing. Passing label={undefined} triggers the default, while label={null} renders nothing for the label.
Forwarding props with spread
When a component wraps another one, you can forward many props at once with the spread operator. The ...rest pattern in the parameter list collects every prop you did not name.
function TextInput({ label, ...inputProps }) {
return (
<label>
{label}
<input {...inputProps} />
</label>
);
}
export default function App() {
return (
<TextInput
label="Email"
type="email"
placeholder="[email protected]"
required
/>
);
}TextInput uses label itself and forwards type, placeholder, and required to the <input>. This keeps wrapper components short.
Props are read-only
A component must treat its props as immutable. Do not assign to props.x, and do not change an object or array that arrived as a prop. React may call your component more than once and may reuse the same objects, so a mutation can cause bugs in places far from the cause.
// Wrong: mutates the array that belongs to the parent
function SortedList({ items }) {
items.sort();
return (
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}
// Right: copy first, then sort the copy
function SortedListFixed({ items }) {
const sorted = [...items].sort();
return (
<ul>
{sorted.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}Array.prototype.sort changes the array in place. The first version reorders the parent's data every time it renders. The second makes a copy and leaves the original alone.
If a value needs to change over time inside a component, it belongs in state, which a later chapter covers. When the parent passes new props, React calls the child again with a new props object. That is how a child shows updated data.
Props are not the same as every attribute
Two names are reserved. key and ref look like props when you write them, but React consumes them and does not pass them to the child. Reading props.key gives undefined. If the child needs the value, pass it under a different name, such as id.
The special children prop holds whatever JSX you nest between a component's opening and closing tags. The next chapter covers it. For now, remember that it arrives in the same props object as everything else.
Common errors
- Quotes instead of braces.
<Counter start="0" />passes the string"0". Thenstart + 1gives"01". Writestart={0}. - Forgetting to destructure. Writing
function Greeting(name)makesnamethe whole props object. Rendering it as{name}throws an error because objects are not valid as a React child. Use({ name })orprops.name. - Calling the function instead of passing it.
onClick={handleClick()}runs the handler during render and passes its return value. UseonClick={handleClick}oronClick={() => handleClick(id)}. - Mutating props. Sorting, pushing to, or reassigning props changes data you do not own. Copy first.
- Using a lowercase component name.
<greeting />is treated as an HTML tag. Component names must start with a capital letter. - Expecting a child to see updates it caused. Assigning to a variable that came from props does not change the parent. Pass a callback instead.
Summary of the model
A parent writes attributes. React turns them into one object. The child function reads that object, usually with destructuring, and returns JSX. Strings use quotes, everything else uses braces, and defaults apply to undefined only. Functions pass as props when a child needs to signal its parent, and the child never changes what it receives.
Exercise
A parent renders <Counter start="5" step={2} />. The child is function Counter({ start, step = 1 }) { return <p>{start + step}</p>; }. What does it render, and how do you fix it so that the result is 7?
Show answer
It renders 52. Because start="5" is a string, + concatenates it with the number 2, producing the string "52". The default step = 1 is not used since step was passed as 2. Fix it by passing a number: start={5}. Then 5 + 2 renders 7.
Exercise
A component Tags({ items }) calls items.reverse() before mapping over the array. The parent's list on the screen elsewhere now appears in reversed order too. Why does this happen, and what is the fix?
Show answer
reverse mutates the array in place, and items is the same array object the parent owns. Props are read-only, so the component must not change it. Copy the array first: [...items].reverse(), and map over the copy.