How to loop inside React JSX
By Flavio
Published · Updated
Tagged: React
Learn how to loop inside React JSX with map(), pick the right key prop, loop over objects or a number of times, use filter() first, and avoid common key mistakes.
Suppose you have a React component and an items array you want to loop over, to print all the “items” you have.
Here’s how you can do it.
In the returned JSX, add a <ul> tag to create a list of items:
return (
<ul>
</ul>
)
Inside this list, we add a JavaScript snippet using curly brackets {} and inside it we call items.map() to iterate over the items.
We pass to the map() method a callback function that is called for every item of the list.
Inside this function we return a <li> (list item) with the value contained in the array, and with a key prop that is set to the index of the item in the array. This is needed by React.
return (
<ul>
{items.map((value, index) => {
return <li key={index}>{value}</li>
})}
</ul>
)
You can also use the shorthand form with implicit return:
return (
<ul>
{items.map((value, index) => <li key={index}>{value}</li>)}
</ul>
)
Watch the braces. If you write => { you open a function body, and you must write return yourself. If you forget it, map() returns an array of undefined and nothing shows up on the page, with no error.
Why can’t I use a for loop inside JSX?
Inside {} in JSX you can only put an expression, something that produces a value. A for loop is a statement. It doesn’t produce a value, so this doesn’t work:
// ❌ syntax error
return (
<ul>
{for (const item of items) { <li>{item}</li> }}
</ul>
)
map() works because it’s an expression that returns a new array, and React knows how to render an array of elements.
If you really prefer a for loop, build the array before the return:
const listItems = []
for (const item of items) {
listItems.push(<li key={item.id}>{item.name}</li>)
}
return <ul>{listItems}</ul>
Which key should I use?
The key tells React which array item each element belongs to. When the list changes, React uses it to match the old elements with the new ones.
The best key is a stable ID that comes with your data, like the ID from your database:
const users = [
{ id: 'u1', name: 'Flavio' },
{ id: 'u2', name: 'Roger' },
]
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
)
The rules from the React docs:
- a key is a string or a number
- keys must be unique among siblings. Two different lists can reuse the same keys.
- keys must not change between renders
If you create the items yourself in the browser, give each one an ID when you create it, for example with crypto.randomUUID(), and store it with the item:
const newTodo = { id: crypto.randomUUID(), text: 'Buy milk' }
When is the index OK as a key?
React uses the index as the key when you don’t pass one. It works fine for a list that never changes order, never gets items inserted or removed, and has no state inside its items.
It breaks when the list changes. Say each <li> has an <input> and you delete the first item. The second item now has index 0, so React thinks it’s the old first item and keeps its state. You end up with text typed into the wrong row.
Don’t generate keys while rendering
This looks like it solves the problem, but it makes it worse:
// ❌ don't do this
{items.map((item) => <li key={Math.random()}>{item.name}</li>)}
The keys are different on every render, so React throws away and recreates every element each time. It’s slow, and any input inside the list loses what the user typed.
The same goes for crypto.randomUUID() called inside map(). Generate the ID once, when you create the item, not while rendering.
The “unique key prop” warning
If you forget the key, React prints this in the console:
Each child in a list should have a unique "key" prop.
The fix is to add key to the outermost element you return from map(). Putting it on an element nested inside doesn’t count:
// ❌ key is on the wrong element
{users.map((user) => (
<li>
<span key={user.id}>{user.name}</span>
</li>
))}
// ✅
{users.map((user) => (
<li key={user.id}>
<span>{user.name}</span>
</li>
))}
My component can’t read props.key
key is only used by React. Your component doesn’t receive it as a prop. If the component needs the ID, pass it a second time with another name:
{users.map((user) => (
<User key={user.id} userId={user.id} name={user.name} />
))}
Rendering more than one element per item
Sometimes each item needs to produce several elements, like a <dt> and a <dd> in a description list. You can’t put a key on the short <>...</> fragment syntax, so import Fragment and use the long form (more on it in React Fragment):
import { Fragment } from 'react'
function Glossary({ terms }) {
return (
<dl>
{terms.map((term) => (
<Fragment key={term.id}>
<dt>{term.name}</dt>
<dd>{term.definition}</dd>
</Fragment>
))}
</dl>
)
}
Filter, then map
To show only some items, call filter() first and then map() on the result:
const activeUsers = users.filter((user) => user.active)
return (
<ul>
{activeUsers.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
)
You can chain them too: users.filter(...).map(...).
Looping over an object
map() is an array method, so it doesn’t exist on plain objects. Turn the object into an array first with Object.entries(), Object.keys() or Object.values():
const prices = { apple: 1.2, banana: 0.5, cherry: 3 }
return (
<ul>
{Object.entries(prices).map(([fruit, price]) => (
<li key={fruit}>
{fruit}: {price} €
</li>
))}
</ul>
)
The object keys are unique, so they make good React keys here.
Looping a number of times
To render something n times when you don’t have an array, create one with Array.from():
function Stars({ count }) {
return (
<div>
{Array.from({ length: count }, (_, i) => (
<span key={i}>⭐</span>
))}
</div>
)
}
Here the index is a fine key, because the items are all the same and never reorder.
Showing a message when the list is empty
An empty array renders nothing. If you want to tell the user, check the length first:
if (items.length === 0) {
return <p>No items yet.</p>
}
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
)Want me to talk about your product? You can sponsor this site.