Rendering lists in React
Written By: Avinash Malhotra
Updated on
Rendering lists in React is a fundamental concept that lets developers display and manage collections of data such as arrays and arrays of objects. Common JavaScript helpers used for this are map(), filter(), and reduce().
This article shows practical examples, common pitfalls, and best practices (especially around keys) to help your lists render efficiently and predictably.
Rendering methods
map()- Transforms each element in a listfilter()- Filters elements based on a conditionreduce()- Reduces a list to a single value
Using map() in React
The map() method is used to iterate over an array and transform its elements. In React, it's commonly used to render lists of components.
Here's an example:
map in Arrays
- Toyota
- Suzuki
- Honda
- Ford
- BMW
function CarsList() {
const cars = ['Toyota', 'Suzuki', 'Honda', 'Ford', 'BMW'];
return (
<ul>
{cars.map((car) => (
<li key={car}>{car}</li>
))}
</ul>
);
}
In the example above, the CarsList component renders a list of car brands using the map() method. Each car brand is displayed as a list item (<li>) within an unordered list (<ul>).
Map in Objects
You can also use the map() method to render lists from an object with key values. Here's an example:
- brand: Suzuki
- model: Swift
- power: 82
- torque: 112
function CarList() {
const car = {
brand: 'Suzuki',
model: 'Swift',
power: 82,
torque: 112,
};
return (
<ul>
{Object.keys(car).map(([key,value]) => (
<li key={key}>{key}: {value} </li>
))}
</ul>
);
}
Note: In a real application, you should provide a unique "key" prop to each list item to help React identify which items have changed, modified or removed from the list.
Using keys in React Lists
When rendering lists in React, it's important to provide a unique "key" prop to each list item. This helps React identify which items have changed, are added, or are removed, improving performance and maintaining the correct state of the list.
function CarsList() {
const cars = ['Toyota', 'Suzuki', 'Honda', 'Ford', 'BMW'];
return (
<ul>
{cars.map((car, index) => (
<li key={index}>{car}</li>
))}
</ul>
);
}
using key from objects id
If you have an array of objects, it's best to use a unique identifier from the object as the key prop. This helps React identify which items have changed, are added, or are removed. Also it improves performance by allowing React to optimize re-renders.
function CarsList() {
const cars = [
{ id: 1, name: 'Toyota' },
{ id: 2, name: 'Suzuki' },
{ id: 3, name: 'Honda' },
{ id: 4, name: 'Ford' },
{ id: 5, name: 'BMW' }
];
return (
<ul>
{cars.map((car) => (
<li key={car.id}>{car.name}</li>
))}
</ul>
);
}
In this example, each car object has a unique id property, which is used as the key prop for each list item.
filter data in array
The filter() method is used to create a new array containing elements that meet a specific condition. In React, it's often used to filter data before rendering it in a component.
Here's an example:
- 2
- 4
- 6
- 8
- 10
function EvenNumbersList() {
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter((number) => number % 2 === 0);
return (
<ul>
{evenNumbers.map((number) => (
<li key={number}>{number}</li>
))}
</ul>
);
}
In this example, the EvenNumbersList component filters the numbers array to include only even numbers using the filter() method. The resulting evenNumbers array is then rendered as a list of items.
filter from array of objects
You can also filter an array of objects based on a specific property. Here's an example:
- Swift
- Baleno
- Alto
function CarsList() {
const cars = [
{ id: 1, name: 'Swift', type: 'hatchback' },
{ id: 2, name: 'Baleno', type: 'hatchback' },
{ id: 3, name: 'Virtus', type: 'sedan' },
{ id: 4, name: 'Brezza', type: 'suv' },
{ id: 5, name: 'Alto', type: 'hatchback' }
];
const hatchbacks = cars.filter((car) => car.type === 'hatchback');
return (
<ul>
{hatchbacks.map((car) => (
<li key={car.id}>{car.name}</li>
))}
</ul>
);
}
In this example, the CarsList component filters the cars array to include only cars of type 'hatchback' using the filter() method. The resulting hatchbacks array is then rendered as a list of items.
Using reduce() in React
The reduce() method is used to reduce an array to a single value by applying a function to each element in the array. In React, it's often used to calculate totals or aggregate data before rendering it in a component.
Here's an example:
Total Price
The total Price: 150
function TotalPrice() {
const prices = [10, 20, 30, 40, 50];
const total = prices.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
return (
<div>
<h2>Total Price</h2>
<p>The total price is: {total}</p>
</div>
);
}
In this example, the TotalPrice component calculates the total price of items in the prices array using the reduce() method. The resulting total is then displayed in the component.
Summary
In this tutorial, we covered how to render lists in React using the map() method. We also explored how to filter data in an array using the filter() method, both for simple arrays and arrays of objects.
- Use the
map()method to transform arrays into lists of components. - Use the
filter()method to create new arrays based on specific conditions. - Always provide a unique "key" prop when rendering lists to help React identify which items have changed.
- For arrays of objects, use a unique identifier from the object as the key prop.
These techniques are essential for building dynamic and responsive user interfaces in React applications.