Sub topic 2
Turning arrays into elements with map
This chapter covers how map converts an array of data into an array of React elements, and what React does with that result. It assumes you know basic JavaScript (arrays, objects, arrow functions, map and filter), basic React (function components, props, JSX), and the useState hook.
The working model
React renders whatever your component returns. JSX can hold a JavaScript expression inside curly braces. If that expression evaluates to an array of elements, React renders each element in order, as siblings.
Array.prototype.map fits this well. It takes an array, calls your function on each item, and returns a new array of the same length. Each call returns one element, so an array of data becomes an array of elements.
const people = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Grace' },
];
function PeopleList() {
return (
<ul>
{people.map(person => (
<li key={person.id}>{person.name}</li>
))}
</ul>
);
}Here people.map(...) runs during rendering and returns an array of two <li> elements. React places both inside the <ul>. The key prop is covered in the next chapters. For now, note that it is there and that it comes from the data, not from the position in the array.
Expressions, not statements
The braces in JSX accept expressions only. An expression produces a value. A for loop or an if statement does not, so you cannot place one between the tags.
// Invalid: a for statement is not an expression
<ul>
{for (const p of people) { <li>{p.name}</li> }}
</ul>map is an expression that returns an array, so it works. You can also build the array before the return and embed it by name:
function PeopleList({ people }) {
const items = people.map(person => (
<li key={person.id}>{person.name}</li>
));
return <ul>{items}</ul>;
}Both forms behave the same way. Use the inline form when the callback is short. Use a named variable when you need extra logic around the callback.
Arrow function bodies: parentheses versus braces
The most common first error with map is a missing return. An arrow function has two body styles.
| Style | Example | Returns |
|---|---|---|
| Expression body | `p => <li>{p.name}</li>` | The expression value, implicitly |
| Block body | `p => { return <li>{p.name}</li>; }` | Only what you `return` |
When the JSX spans several lines, wrap it in parentheses so the implicit return still works:
people.map(person => (
<li key={person.id}>
{person.name}
</li>
));If you switch to curly braces and forget return, the callback returns undefined. The result is an array of undefined values, and React renders nothing for them. The list looks empty, with no error.
// Bug: block body with no return
{people.map(person => {
<li key={person.id}>{person.name}</li>;
})}
// Fix: add return
{people.map(person => {
return <li key={person.id}>{person.name}</li>;
})}Use a block body when you need local variables or several statements before the element:
{people.map(person => {
const label = `${person.name} (#${person.id})`;
return <li key={person.id}>{label}</li>;
})}The callback arguments
map calls your function with three arguments: the item, its index, and the original array.
{people.map((person, index) => (
<li key={person.id}>
{index + 1}. {person.name}
</li>
))}The index is useful for display, such as numbering rows. It is a poor choice for key, because it describes a position and not an identity. A later chapter explains the failure modes.
What happens on each render
map runs again every time the component renders. It does not mutate your data. It produces a fresh array of new element objects, and React compares that result with the previous render to decide which parts of the page to change.
This has two consequences:
- The mapping function should be pure. It should compute elements from its input and not change outside values or call APIs.
- Heavy work inside the callback runs on every render. For a few hundred simple items this is fine. For expensive transformations, compute the data first and keep the callback light.
The diagram below shows the flow from data to screen.
What map can return
The callback can return anything React can render. Common cases:
- A single element, such as
<li>. - A custom component, such as
<PersonRow person={person} />. - A string or number, which becomes text.
null, which renders nothing for that item.
Returning null lets you skip some items while keeping a single map:
{people.map(person =>
person.name ? <li key={person.id}>{person.name}</li> : null
)}For plain exclusion, filtering first is usually clearer, and a later chapter covers that. The null approach is handy when the skip rule depends on something you only know inside the callback.
Also note that map always returns an array of the same length as its input. If you want to change the length, use filter before map, or flatMap if each item should produce zero or more elements.
Edge cases
Empty arrays. Mapping an empty array returns an empty array, and React renders nothing. You get an empty <ul> with no children. Whether that is acceptable depends on the design. Handling empty lists gets its own chapter.
Undefined or null data. Calling .map on undefined throws a TypeError. This often happens when data loads asynchronously and the prop is not yet set. Two options:
function PeopleList({ people = [] }) {
return (
<ul>
{people.map(person => (
<li key={person.id}>{person.name}</li>
))}
</ul>
);
}A default parameter value handles undefined, but not null. For null, use (people ?? []).map(...) or check before mapping.
Objects as children. React cannot render a plain object. If you write {person} where person is { id: 1, name: 'Ada' }, React throws an error saying objects are not valid as a React child. Render a field, such as {person.name}.
Array-like values. map exists on arrays only. A Set, a Map, or the result of Object.entries needs conversion first:
const scores = { Ada: 98, Grace: 95 };
function Scores() {
return (
<ul>
{Object.entries(scores).map(([name, score]) => (
<li key={name}>{name}: {score}</li>
))}
</ul>
);
}Object.entries returns an array of [key, value] pairs, and the callback destructures each pair. For a Set, use Array.from(set).map(...) or [...set].map(...).
Mapping to components
When each item has its own markup, logic, or state, map to a component and pass the item as a prop:
function PersonRow({ person }) {
return <li>{person.name}</li>;
}
function PeopleList({ people }) {
return (
<ul>
{people.map(person => (
<PersonRow key={person.id} person={person} />
))}
</ul>
);
}The key goes on the element returned by map, here <PersonRow />, not on the <li> inside the component. React reads the key from the outermost element in the array, and the component itself never receives it as a prop.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| List renders empty, no error | Block body without `return` | Add `return` or use parentheses with an expression body |
| `TypeError: Cannot read properties of undefined (reading 'map')` | Data is `undefined` on first render | Default to `[]` or guard before mapping |
| "Objects are not valid as a React child" | Rendering an object directly | Render a field of the object |
| Key warning in the console | No `key` on the returned element | Add a stable `key` from the data |
| Key on the wrong element | Key placed inside the component | Move it to the element returned from `map` |
Putting it together
This component uses default props, an index for display only, and ids for keys:
const initialPeople = [
{ id: 'a1', name: 'Ada', role: 'Engineer' },
{ id: 'g2', name: 'Grace', role: 'Admiral' },
{ id: 'k3', name: 'Katherine', role: 'Mathematician' },
];
function Roster({ people = initialPeople }) {
return (
<ol>
{people.map((person, index) => (
<li key={person.id}>
<strong>{index + 1}. {person.name}</strong>
<span> {person.role}</span>
</li>
))}
</ol>
);
}
export default Roster;Exercise
This component shows an empty list even though names holds three strings. What is wrong, and how do you fix it?
function Names({ names }) {
return (
<ul>
{names.map(name => {
<li key={name}>{name}</li>;
})}
</ul>
);
}
Show answer
The callback uses a block body (curly braces) but has no return, so it returns undefined for every item and React renders nothing. Fix it by adding return, as in { return <li key={name}>{name}</li>; }, or by switching to an expression body with parentheses: name => (<li key={name}>{name}</li>).
Exercise
A component receives tags as a Set of strings. Why does tags.map(...) fail, and what is one way to render <li> elements for it?
Show answer
map is defined on arrays, and a Set does not have it, so the call throws a TypeError. Convert the set to an array first, for example Array.from(tags).map(tag => <li key={tag}>{tag}</li>) or [...tags].map(...).