Lists in React
Imagine you have a shopping cart with multiple items. How do you display all those items on the screen? In React, you don't write separate code for each item you use **lists** to render collections of data dynamically.
What are Lists in React?
Lists in React are created by transforming arrays of data into arrays of JSX elements. You typically use the JavaScript `map()` function to loop through an array and return a JSX element for each item.
Rendering lists is one of the most common tasks in React. Whether it's a todo list, product catalog, or comments section, you'll use lists everywhere.
Basic List Rendering
function FruitList() { const fruits = ['Apple', 'Banana', 'Orange', 'Mango'];
return ( <ul> {fruits.map(fruit => ( <li>{fruit}</li> ))} </ul> );}This will render an unordered list with all four fruits. However, if you run this code, you'll see a warning in the console: "Warning: Each child in a list should have a unique 'key' prop." This brings us to the next important concept keys.
Rendering Lists of Objects
In real applications, you'll often work with arrays of objects:
function ProductList() { const products = [ { id: 1, name: 'Laptop', price: 999 }, { id: 2, name: 'Mouse', price: 25 }, { id: 3, name: 'Keyboard', price: 75 } ];
return ( <div> {products.map(product => ( <div key={product.id}> <h3>{product.name}</h3> <p>${product.price}</p> </div> ))} </div> );}Conditional Rendering Within Lists
You can combine list rendering with conditional logic:
function TaskList({ tasks }) { return ( <ul> {tasks.map(task => ( <li key={task.id}> <span style={{ textDecoration: task.completed ? 'line-through' : 'none' }}> {task.text} </span> {task.priority === 'high' && <span> 🔥</span>} </li> ))} </ul> );}Filtering Lists Before Rendering
You can use `filter()` before `map()` to show only specific items:
function ActiveTodos({ todos }) { const activeTodos = todos.filter(todo => !todo.completed);
return ( <ul> {activeTodos.map(todo => ( <li key={todo.id}>{todo.text}</li> ))} </ul> );}Two Minute Drill
- Lists in React are created by transforming arrays into JSX using `map()`.
- Each list item needs a unique `key` prop (usually the item's ID).
- You can combine `filter()` and `map()` to show subsets of data.
- Lists can contain conditional rendering within each item.
- Always use meaningful keys avoid using array index as key if the list can change.
Need more clarification?
Drop us an email at career@quipoinfotech.com
