How to Render List in React: Simple Syntax and Example
In React, you render a list by using 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 items efficiently.Syntax
Use the map() method on your array to return JSX elements. Each element needs a unique key prop to identify it.
array.map(item => <Element key={uniqueKey}>...</Element>): loops over arraykey: unique identifier for each element- JSX element: what you want to render for each item
jsx
const listItems = items.map(item => <li key={item.id}>{item.name}</li>);
Example
This example shows how to render a list of fruits using map(). Each fruit is displayed as a list item with a unique 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 when rendering lists in React include:
- Not providing a
keyprop or using an index as key, which can cause rendering bugs. - Mutating the original array instead of creating a new one.
- Returning non-JSX values inside
map().
jsx
/* Wrong: Using index as key can cause issues when list changes */ const listItemsWrong = items.map((item, index) => <li key={index}>{item.name}</li>); /* Right: Use a unique stable id as key */ const listItemsRight = items.map(item => <li key={item.id}>{item.name}</li>);
Quick Reference
- Always use
keyprop with unique and stable values. - Use
map()to transform arrays into JSX lists. - Do not mutate arrays directly when rendering.
- Wrap list items in a container element like
<ul>or<div>.
Key Takeaways
Use the map() method to convert arrays into JSX elements for rendering lists.
Always provide a unique key prop to each list item to help React track changes.
Avoid using array indexes as keys to prevent rendering bugs.
Wrap list items in a container element like
- or
for proper structure.
Do not mutate the original array when rendering lists; use pure functions.