Handling lists with React
For list handling, we will learn about the JavaScript map()
method, which is useful when you have to manipulate a list. The map()
method creates a new array containing the results of calling a function on each element in the original array. In the following example, each array element is multiplied by 2
:
const arr = [1, 2, 3, 4];
const resArr = arr.map(x => x * 2); // resArr = [2, 4, 6, 8]
The following example code demonstrates a component that transforms an array of integers into an array of list items and renders these inside the ul
element:
import React from 'react';
function MyList() {
const data = [1, 2, 3, 4, 5];
return (
<>
<ul>
{
data.map((number) =>
<li>Listitem {number}</li>)
}
</ul>
</>
);
};
export default MyList;
The following screenshot shows what the component looks like when it is rendered. If you open the console...