How to Use map() to Render Lists in React Components
In React, use the
map() function to transform an array into a list of JSX elements inside your component's return. Each element should have a unique key prop to help React track changes efficiently.Syntax
Use array.map(item => <JSX key={uniqueKey}>...</JSX>) inside your component's return to create a list of elements. The key prop must be unique for each item to help React identify which items changed, added, or removed.
jsx
const listItems = items.map(item => <li key={item.id}>{item.name}</li>); return <ul>{listItems}</ul>;
Output
<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>
Example
This example shows a React functional component rendering a list of fruits using map(). Each fruit is displayed as a list item with a unique key.
jsx
import React from 'react'; function FruitList() { const fruits = [ { id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }, { id: 3, name: 'Cherry' } ]; return ( <ul> {fruits.map(fruit => ( <li key={fruit.id}>{fruit.name}</li> ))} </ul> ); } export default FruitList;
Output
<ul><li>Apple</li><li>Banana</li><li>Cherry</li></ul>
Common Pitfalls
Common mistakes include:
- Not providing a
keyprop or using an index as a key, which can cause rendering bugs. - Returning multiple elements without wrapping them in a parent element or React fragment.
- Mutating the original array instead of creating a new one.
jsx
/* Wrong: Using index as key (can cause issues if list changes) */ const list = items.map((item, index) => <li key={index}>{item.name}</li>); /* Right: Use a unique stable id as key */ const list = items.map(item => <li key={item.id}>{item.name}</li>);
Quick Reference
- Always use a unique
keyprop for list items. - Use
map()inside JSX to render lists dynamically. - Wrap multiple elements in a parent or React fragment.
- Keep list data immutable for predictable rendering.
Key Takeaways
Use
map() to convert arrays into lists of JSX elements in React.Always provide a unique
key prop to each list item for efficient updates.Avoid using array indexes as keys to prevent rendering bugs.
Wrap multiple elements in a parent or React fragment when returning from
map().Keep your list data immutable to ensure React renders updates correctly.