React Lists
Rendering multiple items dynamically
π What are React Lists?
React lists allow you to render multiple similar elements from an array of data. Using the map() function, you can transform each item in an array into a React element, making it easy to display dynamic content.
function FruitList() {
const fruits = ['Apple', 'Banana', 'Orange'];
return (
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
);
}
Output:
- Apple
- Banana
- Orange
Key Concepts for Lists
map() Function
Transform array to elements
array.map(item => <li>{item}</li>)
Keys
Unique identifier for items
<li key={item.id}>{item.name}</li>
Index
Position in array
map((item, index) => ...)
Filter
Show specific items
array.filter(item => condition)
πΉ Basic List Rendering
The most common way to render lists in React is using the map() function. It iterates through each item in your array and returns a JSX element for each one.
function NumberList() {
const numbers = [1, 2, 3, 4, 5];
return (
<div>
<h3>Numbers:</h3>
<ul>
{numbers.map((number) => (
<li key={number}>Number: {number}</li>
))}
</ul>
</div>
);
}
Output:
Numbers:
- Number: 1
- Number: 2
- Number: 3
- Number: 4
- Number: 5
πΉ Lists with Objects
When working with arrays of objects, you can access multiple properties from each item. Always use a unique identifier like an ID as the key prop for better performance and stability.
function UserList() {
const users = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 28 }
];
return (
<div>
{users.map((user) => (
<div key={user.id} style={{ padding: '10px', border: '1px solid #ddd' }}>
<h4>{user.name}</h4>
<p>Age: {user.age}</p>
</div>
))}
</div>
);
}
Output:
Alice
Age: 25
Bob
Age: 30
Charlie
Age: 28
πΉ Understanding Keys
Keys help React identify which items have changed, been added, or removed. They should be unique among siblings and stable across re-renders. Avoid using array indexes as keys when the list can change.
function TodoList() {
const todos = [
{ id: 'todo-1', text: 'Learn React' },
{ id: 'todo-2', text: 'Build a project' },
{ id: 'todo-3', text: 'Deploy to production' }
];
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
// β
Good: Using unique ID
// β Bad: key={index}
Output:
- Learn React
- Build a project
- Deploy to production
πΉ Filtering Lists
You can combine filter() and map() to display only items that meet certain criteria. This is useful for search functionality, category filtering, or showing active items only.
function ProductList() {
const products = [
{ id: 1, name: 'Laptop', inStock: true },
{ id: 2, name: 'Phone', inStock: false },
{ id: 3, name: 'Tablet', inStock: true }
];
return (
<div>
<h3>Available Products:</h3>
<ul>
{products
.filter(product => product.inStock)
.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
);
}
Output:
Available Products:
- Laptop
- Tablet