Rendering lists in React helps show many items on the screen easily. It lets you display things like menus, messages, or products by repeating a small piece of code for each item.
0
0
Rendering lists in React
Introduction
Showing a list of tasks in a to-do app.
Displaying a menu with many options.
Listing messages in a chat app.
Showing products in an online store.
Rendering search results from a query.
Syntax
React
function Component() { const items = [/* array of data */]; return ( <ul> {items.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> ); }
Always add a unique key prop to each list item to help React track changes.
Use map() to transform each item into a React element.
Examples
Rendering a simple list of strings using their index as key.
React
function FruitList() { const fruits = ['Apple', 'Banana', 'Cherry']; return ( <ul> {fruits.map((fruit, index) => ( <li key={index}>{fruit}</li> ))} </ul> ); }
Handling an empty list by showing a message.
React
function EmptyList() { const items = []; return ( <ul> {items.length === 0 ? <li>No items found</li> : items.map(item => <li key={item.id}>{item.name}</li>)} </ul> ); }
Rendering a list with only one item.
React
function SingleItemList() { const items = [{ id: 1, name: 'Only item' }]; return ( <ul> {items.map(item => <li key={item.id}>{item.name}</li>)} </ul> ); }
Rendering a list of objects using a unique string id as key.
React
function ListWithObjects() { const users = [ { id: 'u1', name: 'Alice' }, { id: 'u2', name: 'Bob' }, { id: 'u3', name: 'Charlie' } ]; return ( <ul> {users.map(user => <li key={user.id}>{user.name}</li>)} </ul> ); }
Sample Program
This React component shows a list of tasks. It uses useState to hold tasks. Each task is shown as a list item with a unique key. This helps React update the list efficiently.
React
import React, { useState } from 'react'; function TaskList() { const [tasks, setTasks] = useState([ { id: 101, title: 'Buy groceries' }, { id: 102, title: 'Walk the dog' }, { id: 103, title: 'Read a book' } ]); return ( <main> <h1>My Tasks</h1> <ul> {tasks.map(task => ( <li key={task.id}>{task.title}</li> ))} </ul> </main> ); } export default TaskList;
OutputSuccess
Important Notes
Using a unique key helps React know which items changed, added, or removed. Avoid using indexes as keys if the list can change order.
Rendering large lists can slow down your app. Consider techniques like windowing for very long lists.
Remember to handle empty lists gracefully to improve user experience.
Summary
Use map() to render lists in React.
Always add a unique key prop to each list item.
Handle empty or single-item lists carefully for good UI.