Sub topic 3
Rendering your first list
This chapter assumes you know JavaScript arrays, objects, arrow functions, and map. It also assumes you can write a React function component with props and JSX. You do not need useState here. The data in this chapter is fixed.
By the end, you will turn an array of data into a list of elements. You will also know which mistakes produce errors or warnings, and what they mean.
JSX accepts expressions, and arrays are expressions
Curly braces in JSX let you embed any JavaScript expression. An expression is code that produces a value, such as user.name, 2 + 2, or items.length.
function Greeting({ name }) {
return <h1>Hello, {name.toUpperCase()}</h1>;
}React can render an array as well. It renders each item in order. Strings and numbers become text. React elements become DOM nodes. null, undefined, and booleans render nothing.
function Letters() {
return <p>{['a', 'b', 'c']}</p>;
}This shows abc. The array form is rarely what you want for real data. You usually have objects such as { id: 1, name: 'Ada' }, and you need to turn each one into markup. That is the job of map.
Turning data into elements with map
Array.prototype.map calls a function on every item and returns a new array of the results. The original array does not change. If the function returns a JSX element, the result is an array of elements, and React can render it.
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>
);
}Read it from the inside out:
people.map(...)loops over the array.- For each
person, the arrow function returns an<li>element. mapcollects these into a new array of two<li>elements.- The outer
{ }embeds that array inside the<ul>.
The rendered output is:
<ul>
<li>Ada</li>
<li>Grace</li>
</ul>The key prop does not appear in the output. React uses it internally. The next chapter explains why every list item needs one. For now, include it and use a unique id from your data.
Where the map call belongs
The map call is an expression, so it can go anywhere an expression is allowed. Two placements are common.
Inline inside JSX
This is the form above. It works well when the item markup is short.
In a variable before the return
When the markup grows, or you want to name the step, build the array first:
function PeopleList() {
const items = people.map(person => (
<li key={person.id}>{person.name}</li>
));
return <ul>{items}</ul>;
}Both forms behave the same. Choose the one that reads better. A component that does a lot of work inside return is easier to follow when the list is built above it.
Arrow function bodies: parentheses versus braces
This is the most common first mistake. An arrow function has two body styles:
x => ( ... )orx => exprreturns the value implicitly.x => { ... }is a block body. It returns nothing unless you writereturn.
This version is wrong:
function PeopleList() {
return (
<ul>
{people.map(person => {
<li key={person.id}>{person.name}</li>;
})}
</ul>
);
}The braces make a block, and the block has no return. map produces [undefined, undefined], and React renders nothing. There is no error, so the list is silently empty. The fix is either to switch to parentheses or to add return:
{people.map(person => {
return <li key={person.id}>{person.name}</li>;
})}Use the block form when you need statements before the element, for example computing a local value:
{people.map(person => {
const label = `${person.name} (#${person.id})`;
return <li key={person.id}>{label}</li>;
})}Rendering more than text
Each item can be any JSX, including your own components and attributes computed from the data.
const products = [
{ id: 'p1', name: 'Keyboard', price: 49.5, url: '/keyboard' },
{ id: 'p2', name: 'Mouse', price: 19, url: '/mouse' },
];
function ProductList() {
return (
<ul>
{products.map(product => (
<li key={product.id}>
<a href={product.url}>{product.name}</a>
{' '}
<span>${product.price.toFixed(2)}</span>
</li>
))}
</ul>
);
}Two details are worth noting. {' '} inserts a literal space, because JSX trims whitespace across line breaks. In ${product.price.toFixed(2)}, the first $ is plain text and {product.price.toFixed(2)} is the expression.
Rendering an object's entries
map is an array method, so it does not exist on plain objects. Convert the object to an array first. Object.entries returns [key, value] pairs:
const stock = { apples: 12, pears: 0, plums: 7 };
function StockList() {
return (
<ul>
{Object.entries(stock).map(([fruit, count]) => (
<li key={fruit}>
{fruit}: {count}
</li>
))}
</ul>
);
}The object's own property names are unique, so they work as keys here. The parameter ([fruit, count]) destructures each pair.
Lists inside lists
Nested data needs a nested map. Each level has its own list, so each level needs its own keys. Keys only have to be unique among siblings, not across the whole page.
const teams = [
{ id: 't1', name: 'Frontend', members: ['Ada', 'Linus'] },
{ id: 't2', name: 'Backend', members: ['Grace', 'Ken'] },
];
function Teams() {
return (
<div>
{teams.map(team => (
<section key={team.id}>
<h2>{team.name}</h2>
<ul>
{team.members.map(member => (
<li key={member}>{member}</li>
))}
</ul>
</section>
))}
</div>
);
}Here the member names serve as keys only because each name is unique within its team. If two members could share a name, you would need an id. The next chapter covers how to choose.
Running it
This is a complete example you can run in a project created with Vite's React template. Put it in src/main.jsx:
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
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>
);
}
createRoot(document.getElementById('root')).render(
<StrictMode>
<PeopleList />
</StrictMode>
);Common errors and what they mean
| Symptom | Likely cause | Fix |
|---|---|---|
| Console warning: each child in a list should have a unique "key" prop | The element returned from `map` has no `key`, or the key is on a wrapper inside it | Put `key` on the outermost element returned by the callback |
| List is empty and there is no error | Block-body arrow function with no `return` | Use parentheses or add `return` |
| `Objects are not valid as a React child` | You rendered an object, for example `{person}` instead of `{person.name}` | Render a string or number field, or map the object to elements |
| `Cannot read properties of undefined (reading 'map')` | The data is `undefined` when the component first renders | Provide a default such as `items = []`, or guard with an early return |
| Warning about duplicate keys | Two items share the same key value | Use a field that is unique, such as an id |
Guarding against missing data
Data often arrives late, for example from a network request. A map call on undefined throws and breaks the whole component. A default parameter handles the simplest case:
function PeopleList({ people = [] }) {
return (
<ul>
{people.map(person => (
<li key={person.id}>{person.name}</li>
))}
</ul>
);
}The default applies only when the prop is undefined. It does not apply when the prop is null. If your data source can return null, use (people ?? []).map(...) instead. Showing a friendly message when the array is empty is a separate topic, covered in a later chapter on empty states.
Summary of the working model
mapreturns a new array of elements, and React renders that array in order.- The callback must return the element. Parentheses return implicitly, and braces need
return. - Each element returned from
mapneeds akey, placed on the outermost element. - Objects need
Object.entries(orObject.values) before they can be mapped. - Nested data needs a nested
map, with keys unique among siblings.
Exercise
The component below renders an empty <ul> and logs no errors. Why, and how do you fix it? Also, what would change if colors were an object such as { red: '#f00', blue: '#00f' } instead of an array?
function Colors({ colors }) {
return (
<ul>
{colors.map(color => {
<li key={color}>{color}</li>;
})}
</ul>
);
}
Show answer
The arrow function uses a block body (curly braces) and has no return, so map produces an array of undefined values and React renders nothing. Fix it by using parentheses, color => (<li key={color}>{color}</li>), or by adding return before the <li>. For an object, map does not exist on it, so calling colors.map would throw a TypeError. Convert it first with Object.entries(colors).map(([name, hex]) => <li key={name}>{name}: {hex}</li>).