Sub topic 5
Passing data with props
This chapter assumes you know JavaScript functions, objects, destructuring, and ES modules. It also assumes you know basic HTML and have read the earlier chapters on components and JSX. You do not need to run anything to follow along. If you want to, put the examples in the src folder of a Vite React project.
What props are
Props (short for properties) are the inputs to a component. A component is a function, and props are the single argument that function receives. React builds that argument as an object from the attributes you write in JSX.
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>
}
export default function App() {
return <Greeting name="Ada" />
}React calls Greeting({ name: "Ada" }) and uses the returned markup. The attribute name="Ada" became the property name on the props object.
Props let one component definition produce many different outputs. They are also how a parent component passes data down to its children.
Destructuring props
Most components destructure the props object in the parameter list. This names each input and removes the repeated props. prefix.
function Greeting({ name, punctuation = '!' }) {
return <h1>Hello, {name}{punctuation}</h1>
}
export default function App() {
return (
<>
<Greeting name="Ada" />
<Greeting name="Grace" punctuation="?" />
</>
)
}The default value punctuation = '!' applies only when the prop is undefined. Passing null does not trigger the default. That difference causes bugs when data comes from an API that returns null for missing values.
Passing values that are not strings
A quoted attribute is always a string. To pass anything else, use curly braces, which evaluate a JavaScript expression.
function Profile({ name, age, skills, active }) {
return (
<section>
<h2>{name} ({age})</h2>
<p>{active ? 'Online' : 'Offline'}</p>
<ul>
{skills.map(skill => <li key={skill}>{skill}</li>)}
</ul>
</section>
)
}
export default function App() {
return (
<Profile
name="Ada"
age={36}
skills={['math', 'code']}
active
/>
)
}Here age={36} passes a number, and skills={[...]} passes an array. Writing active with no value is shorthand for active={true}.
The table below summarizes the common forms.
| JSX | Value the component receives |
|---|---|
| `title="Hi"` | The string `"Hi"` |
| `count={3}` | The number `3` |
| `count="3"` | The string `"3"` |
| `done` | The boolean `true` |
| `done={false}` | The boolean `false` |
| `items={[1, 2]}` | An array |
| `user={{ name: 'Ada' }}` | An object (the outer braces are JSX, the inner braces are the object literal) |
| `onSave={handleSave}` | A function |
Passing functions as props
A parent can pass a function to a child. The child calls it when something happens. This is how a child reports events upward, even though data only flows down.
import { useState } from 'react'
function AddButton({ onAdd }) {
return <button onClick={onAdd}>Add one</button>
}
export default function App() {
const [total, setTotal] = useState(0)
return (
<main>
<p>Total: {total}</p>
<AddButton onAdd={() => setTotal(total + 1)} />
</main>
)
}The state lives in App. AddButton has no state of its own. It only calls onAdd. A common naming convention is onSomething for function props, such as onAdd, onChange, and onSelect.
A frequent mistake is writing onClick={onAdd()}. That calls the function during rendering and passes its result. Pass the function itself: onClick={onAdd}.
The special children prop
Anything you put between a component's opening and closing tags arrives as the children prop.
function Card({ title, children }) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
)
}
export default function App() {
return (
<Card title="Welcome">
<p>This paragraph is the children prop.</p>
<button>Continue</button>
</Card>
)
}children makes layout components possible. Card does not need to know what goes inside it.
Spreading props
The spread syntax passes every property of an object as a separate prop.
function Avatar({ src, alt, size = 48 }) {
return <img src={src} alt={alt} width={size} height={size} />
}
export default function App() {
const photo = { src: '/ada.png', alt: 'Ada Lovelace', size: 64 }
return <Avatar {...photo} />
}This is equivalent to writing src, alt, and size by hand. Use it with care. Spreading a large object into a component hides which props the component actually uses, and it can forward unwanted props to a DOM element.
Props are read-only
A component must never change its own props. Treat the props object as immutable.
// Wrong: mutates the props object
function Bad(props) {
props.name = props.name.toUpperCase()
return <p>{props.name}</p>
}
// Right: compute a new value
function Good({ name }) {
const shout = name.toUpperCase()
return <p>{shout}</p>
}The same rule applies to objects and arrays you receive as props. Calling items.push(x) or items.sort() on a prop array changes the parent's data. Copy first with [...items].sort() or use items.toSorted() in current runtimes.
If a component needs a value that changes over time, that value belongs in state, not in props. Props are what the parent decides. State is what the component remembers. The next chapter covers state in detail.
Props and re-rendering
When a parent re-renders, React calls its children again with the new props. Each render sees a fixed snapshot of props. A child does not need to watch for changes. It simply runs again with new inputs.
By default a child re-renders whenever its parent does, even if the props are identical. For most apps this is fast enough, and you should not optimize it early.
Common errors
- Using
classinstead ofclassName. JSX attributes follow DOM property names, so useclassNameandhtmlFor. - Reading a prop that was never passed. The value is
undefined. Callingskills.mapon it throwsCannot read properties of undefined. Give the prop a default, such asskills = [], or check it before use. - Passing a number as a string.
count="3"plus1gives"31". Usecount={3}. - Calling a function prop during render. Write
onClick={handle}oronClick={() => handle(id)}, notonClick={handle(id)}. - Forgetting that
keyis not a prop. React useskeyfor list identity and does not pass it to the component. If the child needs the value, pass it under another name such asid. - Mutating props. This causes bugs that are hard to trace, because the parent's data changes without the parent knowing.
Exercise
A component is defined as function Badge({ label, count = 0 }). What does it receive in each case: <Badge label="New" />, <Badge label="New" count={null} />, and <Badge label="New" count="5" />?
Show answer
In the first case, count is 0 because the prop is undefined and the default applies. In the second case, count is null, because defaults apply only to undefined. In the third case, count is the string "5", not the number 5, because a quoted attribute is always a string.
Exercise
This code logs an error or behaves wrongly. Identify the problem and fix it: <button onClick={remove(item.id)}>Remove</button>
Show answer
remove(item.id) runs while React renders, and its return value is passed to onClick. Pass a function instead: <button onClick={() => remove(item.id)}>Remove</button>.