React Lists
Learn how to display lists of data in React using the map function and keys.
Lists let you display multiple items in React - like a shopping list, user list, or product catalog.
Displaying Lists
Use JavaScript's `.map()` function to display arrays in React:
```javascript function FruitList() { const fruits = ['Apple', 'Banana', 'Orange'];
return ( <ul> {fruits.map((fruit, index) => ( <li key={index}>{fruit}</li> ))} </ul> ); } ```
**Output:** - Apple - Banana - Orange
The key Prop
Every list item needs a unique `key` prop. This helps React track which items changed.
### Using Index as Key
```javascript {items.map((item, index) => ( <li key={index}>{item}</li> ))} ```
### Using Unique ID as Key (Better!)
```javascript const users = [ { id: 1, name: 'John' }, { id: 2, name: 'Sarah' }, { id: 3, name: 'Mike' } ];
function UserList() { return ( <ul> {users.map((user) => ( <li key={user.id}>{user.name}</li> ))} </ul> ); } ```
List of Objects
When you have objects in an array:
```javascript function ProductList() { const products = [ { id: 1, name: 'Phone', price: 699 }, { id: 2, name: 'Laptop', price: 1299 }, { id: 3, name: 'Tablet', price: 499 } ];
return ( <div> {products.map((product) => ( <div key={product.id}> <h3>{product.name}</h3> <p>${product.price}</p> </div> ))} </div> ); } ```
List with Components
Create a separate component for list items:
```javascript function TodoItem({ todo }) { return ( <div> <h4>{todo.title}</h4> <p>{todo.description}</p> </div> ); }
function TodoList() { const todos = [ { id: 1, title: 'Learn React', description: 'Complete tutorial' }, { id: 2, title: 'Build Project', description: 'Create todo app' } ];
return ( <div> {todos.map((todo) => ( <TodoItem key={todo.id} todo={todo} /> ))} </div> ); } ```
Lists with Events
Add interactivity to list items:
```javascript function NameList() { const names = ['John', 'Sarah', 'Mike', 'Emma'];
const handleClick = (name) => { alert(`You clicked ${name}`); };
return ( <ul> {names.map((name, index) => ( <li key={index} onClick={() => handleClick(name)} style={{ cursor: 'pointer' }} > {name} </li> ))} </ul> ); } ```
Dynamic Lists with State
Add and remove items from lists:
```javascript function ShoppingList() { const [items, setItems] = useState(['Milk', 'Bread', 'Eggs']); const [newItem, setNewItem] = useState('');
const addItem = () => { if (newItem.trim()) { setItems([...items, newItem]); setNewItem(''); } };
const removeItem = (index) => { setItems(items.filter((_, i) => i !== index)); };
return ( <div> <h2>Shopping List</h2>
<input value={newItem} onChange={(e) => setNewItem(e.target.value)} placeholder="Add item" /> <button onClick={addItem}>Add</button>
<ul> {items.map((item, index) => ( <li key={index}> {item} <button onClick={() => removeItem(index)}> Remove </button> </li> ))} </ul> </div> ); } ```
Filtering Lists
Show only certain items:
```javascript function UserList() { const [search, setSearch] = useState('');
const users = [ { id: 1, name: 'John Smith', age: 25 }, { id: 2, name: 'Sarah Johnson', age: 30 }, { id: 3, name: 'Mike Davis', age: 22 } ];
const filteredUsers = users.filter((user) => user.name.toLowerCase().includes(search.toLowerCase()) );
return ( <div> <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search users..." />
<ul> {filteredUsers.map((user) => ( <li key={user.id}> {user.name} - {user.age} years old </li> ))} </ul> </div> ); } ```
Empty List Message
Show a message when list is empty:
```javascript function TaskList() { const tasks = [];
return ( <div> {tasks.length === 0 ? ( <p>No tasks yet! Add your first task.</p> ) : ( <ul> {tasks.map((task, index) => ( <li key={index}>{task}</li> ))} </ul> )} </div> ); } ```
Common Mistakes
### ❌ Forgetting the key
```javascript {items.map((item) => <li>{item}</li>)} ```
### ✅ Always add key
```javascript {items.map((item, index) => <li key={index}>{item}</li>)} ```
### ❌ Using non-unique keys
```javascript {items.map((item) => <li key="same">{item}</li>)} ```
### ✅ Use unique keys
```javascript {items.map((item) => <li key={item.id}>{item}</li>)} ```
Remember
- Use `.map()` to display lists - Always add a unique `key` prop - Use object IDs as keys when available - Filter lists with `.filter()` - Combine lists with state for dynamic updates - Show empty state messages when list is empty
> Next: Learn React Forms - Handle user input professionally!