Handling lists with React
For list handling, we will learn about a new 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 to 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 map()
method also has index
as a second argument, which is useful when handling lists in React. List items in React need a unique key that is used to detect rows that have been updated, added, or deleted.
The following example code demonstrates a component that transforms an array of integers to 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 ( <div> ...