How to Render List in JSX in React: Simple Guide
To render a list in JSX, use the
map() method on an array to create an array of JSX elements. Each element must have a unique key prop to help React track changes efficiently.Syntax
Use the map() function on an array to transform each item into a JSX element. Add a unique key prop to each element for React to identify them.
array.map(item => <Element key={uniqueKey}>...</Element>): transforms each itemkey: unique identifier for each element
jsx
const listItems = items.map(item => <li key={item.id}>{item.name}</li>);
Example
This example shows how to render a list of fruits as an unordered list in JSX. Each fruit has a unique id used as the key.
jsx
import React from 'react'; export default 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> ); }
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 fragment.
jsx
/* Wrong: Using index as key (can cause issues if list changes) */ const listItemsWrong = items.map((item, index) => <li key={index}>{item.name}</li>); /* Right: Use unique id as key */ const listItemsRight = items.map(item => <li key={item.id}>{item.name}</li>);
Quick Reference
| Concept | Description |
|---|---|
| map() | Transforms array items into JSX elements |
| key prop | Unique identifier for each element to optimize rendering |
| JSX element | Returned inside map to display each item |
| Fragment or parent | Wrap multiple elements if needed |
Key Takeaways
Use the map() method to convert arrays into JSX lists.
Always provide a unique key prop for each list element.
Avoid using array index as key to prevent rendering bugs.
Wrap multiple elements in a fragment or parent element.
Rendering lists in JSX is simple and efficient with these patterns.