Sub topic 4
Passing numbers, booleans, objects, arrays, and functions
This chapter assumes you can write a function component, read props from its parameter, and destructure them. You should also be comfortable with JavaScript objects, arrays, and arrow functions. The goal is to understand exactly what a prop can hold and what happens when the value is not a string.
Strings versus expressions
JSX has two ways to give a prop a value.
- Quotes pass a string literal:
name="Ada". - Curly braces pass the result of any JavaScript expression:
size={64}.
The quotes form is only for strings. Everything else needs braces. Writing size="64" passes the string "64", not the number 64. In arithmetic this can work by accident, as in "64" * 2. With + it breaks: "64" + 2 gives "642".
function Avatar({ name, size = 48, rounded = true }) {
const style = {
width: size,
height: size,
borderRadius: rounded ? '50%' : 0,
};
return <div style={style}>{name[0]}</div>;
}
export default function App() {
return (
<>
<Avatar name="Grace" />
<Avatar name="Linus" size={64} rounded={false} />
</>
);
}The first Avatar uses both defaults. The second passes a number and a boolean through braces. The style object is built inside the component and handed to the DOM element.
Braces accept any expression: a variable, a function call, a ternary, or a template string. They do not accept statements such as if or for.
<Avatar name={user.firstName + ' ' + user.lastName} size={isLarge ? 96 : 48} />The value types
| Value | How to pass it | Notes |
|---|---|---|
| String | `title="Hi"` or `title={text}` | Quotes only work for literals. |
| Number | `size={64}` | Never `size="64"` unless you want a string. |
| Boolean | `rounded={false}` or `disabled` | A bare attribute means `true`. |
| Object | `user={{ name: 'Ada' }}` | The double braces are one pair for JSX and one for the object literal. |
| Array | `items={[1, 2, 3]}` | Usually a variable, not a literal. |
| Function | `onSave={handleSave}` | Pass the function itself, not its result. |
| null / undefined | `icon={null}` | Passing `undefined` triggers default values. |
Booleans
Writing a prop with no value is shorthand for true.
<Avatar name="Ada" rounded /> // rounded is true
<Avatar name="Ada" rounded={true} /> // same thing
<Avatar name="Ada" rounded={false} />To pass false, you must use braces. Leaving the attribute out gives undefined, not false. That matters when a default of true is in effect. In the Avatar above, omitting rounded gives you a round avatar, because undefined triggers the default.
Objects and the double braces
The double braces confuse many learners, but nothing special is happening. The outer pair is the JSX expression slot. The inner pair is an ordinary object literal.
function UserBadge({ user }) {
return (
<p>
{user.name} ({user.role})
</p>
);
}
export default function App() {
const user = { name: 'Ada', role: 'admin' };
return (
<>
<UserBadge user={user} />
<UserBadge user={{ name: 'Linus', role: 'editor' }} />
</>
);
}Passing one object is often cleaner than passing five separate props. The trade-off is that the child now depends on the shape of that object. If user.role is renamed, every consumer must change.
Arrays
Arrays are usually rendered with map. Each rendered element needs a key, which a later chapter covers. For now, use a stable unique value such as an id.
function TagList({ tags }) {
return (
<ul>
{tags.map((tag) => (
<li key={tag.id}>{tag.label}</li>
))}
</ul>
);
}
export default function App() {
const tags = [
{ id: 1, label: 'react' },
{ id: 2, label: 'props' },
];
return <TagList tags={tags} />;
}A common defensive pattern is a default of an empty array, so that tags.map never throws when the parent omits the prop.
function TagList({ tags = [] }) {
return (
<ul>
{tags.map((tag) => (
<li key={tag.id}>{tag.label}</li>
))}
</ul>
);
}Functions
A function is a value like any other. You can pass it down and the child can call it later.
function LikeButton({ onLike }) {
return <button onClick={onLike}>Like</button>;
}
export default function Post() {
const handleLike = () => console.log('liked');
return <LikeButton onLike={handleLike} />;
}The next chapters on callback props build on this. Here, focus on one rule: pass the function, do not call it.
Common errors
Calling the function instead of passing it
// Wrong: runs handleLike during render and passes its return value (undefined)
<LikeButton onLike={handleLike()} />
// Right: passes the function
<LikeButton onLike={handleLike} />If the handler needs an argument, wrap it in an arrow function.
<LikeButton onLike={() => handleLike(post.id)} />The wrapper is a new function that React stores. React calls it on click, and it then calls handleLike(post.id).
Passing a string where a number is expected
<Avatar name="Ada" size="64" />Here size is "64". In the Avatar, the browser accepts width: "64" in some cases and not in others, because React adds px to numbers but not to strings. Type checking, covered later in this tutorial, catches this class of bug before the code runs.
Rendering an object as a child
function Show({ user }) {
return <p>{user}</p>; // throws: Objects are not valid as a React child
}React can render strings, numbers, and elements, and arrays of those. It cannot render a plain object. Read a property instead, as in {user.name}.
Booleans, null, and undefined render nothing. That is why {isAdmin && <AdminPanel />} works. Be careful with numbers, though.
{items.length && <List items={items} />} // renders "0" when the list is empty
{items.length > 0 && <List items={items} />} // renders nothingExpecting `false` to appear as text
{false} renders nothing, so <p>{isActive}</p> shows an empty paragraph. Convert it explicitly, for example {String(isActive)} or {isActive ? 'Yes' : 'No'}.
Reference equality
Primitive props (strings, numbers, booleans) compare by value. Objects, arrays, and functions compare by reference. An object literal written in JSX creates a new object on every render.
function Parent() {
return <Chart options={{ color: 'red' }} />; // new object each render
}The child receives an object that has the same contents but a different identity each time. This is harmless in most components. It matters when the child is wrapped in memo, or when the prop is a dependency of an effect, because both compare by reference. A later chapter on re-rendering returns to this. For now, remember the rule: equal contents do not mean equal references.
const a = { color: 'red' };
const b = { color: 'red' };
console.log(a === b); // false
console.log(a === a); // trueThe following diagram shows what flows from parent to child for each kind of value.
Edge cases
- Default values only apply to
undefined.size={null}does not trigger a default of 48. The child receivesnull. Usesize={undefined}or omit the prop to get the default. - A prop named with a dash needs quotes in destructuring.
aria-labelanddata-idare valid JSX attributes, but they cannot be destructured as plain identifiers. Collect them with the rest pattern or readprops['aria-label']. - Props are not cloned. If you pass an object, the child gets the same object the parent holds. The child must not change it. The next chapter explains why.
- Inline styles take objects.
style="color: red"is invalid in JSX. Usestyle={{ color: 'red' }}. classisclassName. Many DOM attributes use camelCase names in JSX, such astabIndexandonClick.
Exercise
A parent renders <Counter start="5" step={2} />. Inside Counter, the code computes start + step. What does it produce, and how do you fix the call site?
Show answer
It produces the string "52", because start="5" passes a string and + concatenates a string with a number. Fix it by passing a number: <Counter start={5} step={2} />.
Exercise
Why does <button onClick={handleDelete(item.id)}>Delete</button> cause trouble, and what is the correct form?
Show answer
The call runs during render, and its return value (usually undefined) becomes the onClick prop. Pass a function instead: onClick={() => handleDelete(item.id)}.
Exercise
A component shows 0 on screen when its list is empty, using {items.length && <List items={items} />}. Rewrite the line so nothing renders for an empty list.
Show answer
Use a boolean condition: {items.length > 0 && <List items={items} />}. The comparison yields false for an empty list, and React renders nothing for false.