Sub topic 2
Passing props and reading them in a component
What this chapter assumes
This chapter assumes you know basic JavaScript: functions, objects, destructuring, and arrow functions. It also assumes you know HTML and have a rough idea of what a React component is. You should be able to run a React project, for example one created with Vite, so you can try the examples.
By the end, you will be able to pass props to a component, read them in the child, and avoid the common mistakes that come up in the first week of using them.
The working model
Props are the inputs a component receives from its parent. A component is a function. React calls it with one argument, a plain object called the props object, and the function returns JSX that describes what to show.
Every attribute you write on a component tag becomes a key on that object. The attribute name becomes the key, and the attribute value becomes the value.
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
export default function App() {
return <Greeting name="Ada" />;
}When React renders <Greeting name="Ada" />, it calls Greeting({ name: "Ada" }). The curly braces in {props.name} tell JSX to evaluate a JavaScript expression and insert the result. The output is Hello, Ada!.
The next diagram shows the direction of the data.
Data moves one way, from parent to child. A child cannot reach up and change what its parent passed. Later chapters cover how a child asks for changes.
Passing props
You pass props the same way you write HTML attributes.
function Badge(props) {
return (
<span>
{props.label} ({props.count})
</span>
);
}
export default function App() {
return (
<div>
<Badge label="Inbox" count={3} />
<Badge label="Drafts" count={0} />
</div>
);
}There are two ways to write a value:
- A quoted string, such as
label="Inbox", passes a string. - Curly braces, such as
count={3}, pass the result of any JavaScript expression.
Writing count="3" would pass the string "3", not the number 3. This difference matters later, when you compare or calculate with the value. A later chapter covers curly-brace values for numbers, booleans, objects, arrays, and functions in detail.
Each use of a component gets its own props object. The two Badge elements above do not share anything.
Reading props
The props object is the first and only parameter of a function component. You can name it anything, but props is the convention.
function Product(props) {
return (
<article>
<h2>{props.title}</h2>
<p>Price: ${props.price}</p>
</article>
);
}Reading a prop is just reading a property from an object. That means the usual JavaScript rules apply. If the parent did not pass a prop, its value is undefined. React does not raise an error for this, and JSX renders undefined as nothing.
function Product(props) {
// If the parent forgot `title`, props.title is undefined
// and the <h2> renders empty.
return <h2>{props.title}</h2>;
}
export default function App() {
return <Product price={10} />;
}The page shows an empty heading, and the console shows no warning. Missing props fail quietly, which is one reason the TypeScript chapter later in this tutorial is useful.
Reading nested values
Props can hold objects. You read inside them with normal property access.
function UserCard(props) {
return (
<p>
{props.user.name} lives in {props.user.address.city}.
</p>
);
}
export default function App() {
const user = { name: "Grace", address: { city: "New York" } };
return <UserCard user={user} />;
}If user were missing, props.user.name would throw TypeError: Cannot read properties of undefined. Unlike a missing top-level prop, a missing object makes the render crash. Guard against this when the object is optional, for example with props.user?.name.
A shorter way to read props
Writing props. before every value gets repetitive. Because props is an ordinary object, you can destructure it. You can do this inside the function body or directly in the parameter list.
function Product(props) {
const { title, price } = props;
return (
<article>
<h2>{title}</h2>
<p>Price: ${price}</p>
</article>
);
}
function ProductShort({ title, price }) {
return (
<article>
<h2>{title}</h2>
<p>Price: ${price}</p>
</article>
);
}Both versions behave the same. The parameter-list form is the most common in modern code, because the function signature then shows which props the component uses. The next chapter covers default values in the parameter list.
Props and JSX tag names
A component name must start with a capital letter. React uses the first letter to decide what a tag means.
| Tag | React treats it as |
|---|---|
| `<div />` | A built-in HTML element |
| `<Greeting />` | A component you defined |
| `<greeting />` | A built-in element named "greeting", which is not what you meant |
If you write <greeting name="Ada" />, React does not call your function. It creates an unknown HTML element and your component never runs.
Props on built-in elements
Built-in elements also take props, which React converts into DOM attributes. Most match HTML, with a few renamed:
| HTML | JSX prop |
|---|---|
| `class` | `className` |
| `for` | `htmlFor` |
| `onclick` | `onClick` |
| `tabindex` | `tabIndex` |
Event props and the style prop take JavaScript values, not strings. For example, style takes an object, so you write style={{ width: 10 }} with two pairs of braces: one for the JSX expression and one for the object literal.
Common errors
These mistakes account for most early problems with props.
- Using lowercase component names. Described above. The component never runs.
- Passing a number as a string.
count="3"gives"3". Adding 1 gives"31", not 4. - Reading a prop under the wrong name. Props are matched by name. If the parent passes
userNameand the child readsprops.username, the value isundefined. JavaScript names are case-sensitive. - Destructuring the wrong shape.
function Badge(label, count)does not work, because the first argument is the whole props object. You needfunction Badge({ label, count }). - Assigning to props.
props.count = 5is not allowed in React's model. A later chapter explains why props are read-only. - Reading a nested value of a missing object. This throws, as shown earlier.
Here is the fourth mistake in code, with the fix:
// Wrong: label receives the whole props object
function BadgeWrong(label, count) {
return <span>{label} ({count})</span>;
}
// Right: destructure the first argument
function BadgeRight({ label, count }) {
return <span>{label} ({count})</span>;
}With BadgeWrong, React tries to render the props object as a child, and you get an error saying objects are not valid as a React child.
How React builds the props object
Knowing the mechanism helps with debugging. The JSX line <Badge label="Inbox" count={3} /> compiles to a call equivalent to this:
jsx(Badge, { label: "Inbox", count: 3 });The result is an element: a small plain object that records the component type and its props. React keeps these elements in memory and decides when to call your function with element.props.
Two consequences follow:
- Props are collected at the moment the parent renders. A child sees a snapshot of the values from that render.
- If the parent renders again with new values, React calls the child again with a new props object. The old object is not modified.
Edge cases to know
- An attribute with no value is
true.<Toggle disabled />passesdisabled: true. This is the same asdisabled={true}. - Later duplicates win. In
<Badge label="A" label="B" />, the last value would be used, and linters flag it. Avoid duplicates. - Attribute names with dashes. Props such as
data-idandaria-labelare valid. Read them with bracket notation,props["data-id"], since a dash is not allowed in a plain identifier. - Text between tags is not an attribute. It arrives under a different name,
children, which a later chapter explains.
function Field(props) {
return (
<input
aria-label={props["aria-label"]}
data-id={props["data-id"]}
/>
);
}
export default function App() {
return <Field aria-label="Search" data-id="42" />;
}Try it yourself
In a Vite React project, replace the contents of src/App.jsx with this complete file, then run npm run dev.
function Profile({ name, role, years }) {
return (
<section>
<h2>{name}</h2>
<p>
{role}, {years} years of experience
</p>
</section>
);
}
export default function App() {
return (
<div>
<Profile name="Ada" role="Engineer" years={5} />
<Profile name="Grace" role="Admiral" years={30} />
</div>
);
}Then try removing years from one Profile tag. The page still renders, with the number missing from the sentence. This confirms that a missing prop is undefined, not an error.
Exercise
A parent renders <Score value="10" />, and the child computes props.value + 1. What does the child get, and how do you fix the parent so the result is 11?
Show answer
The child gets the string "101", because "10" is a string and + concatenates. Change the parent to <Score value={10} />, which passes the number 10, so the sum is 11.
Exercise
You write function Card(title, body) { ... } and use <Card title="Hi" body="Text" />. The page throws an error about objects not being valid as a React child. What is wrong, and what is the corrected signature?
Show answer
React passes a single props object as the first argument, so title holds the whole props object and body is undefined. Rendering title fails because it is an object. Destructure instead: function Card({ title, body }) { ... }.