Handling lists with React

For list handling, we introduce a new JavaScript method, map(), which is handy 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 two:

const arr = [1, 2, 3, 4];

const resArr = arr.map(x => x * 2); // resArr = [2, 4, 6, 8]

The map() method also has the index second argument, which is useful when handling lists in React. The list items in React need a unique key that is used to detect rows that have been changed, added, or deleted.

The following example shows components that transform the array of integers to the array of list items and render these in the ul element. The component is now defined using the ES6 function:

import React from 'react';

const MyList = () => {
const data = [1, 2, 3, 4, 5];

const rows = data.map((number, index) =>
<li key={index}>Listitem {number}</li>
);

return (
<div>
<ul>{rows}</ul>
</div>
);
};

export default MyList;

The following screenshot shows what the component looks like when it is rendered:

If the data is an array of objects, it would be nicer to present the data in table format. We do this in roughly the same way as we did with the list, but now we just map the array to table rows and render these in the table element, as shown in the following component code:

import React from 'react';

const MyList = () => {
const data = [{brand: 'Ford', model: 'Mustang'},
{brand:'VW', model: 'Beetle'}, {brand: 'Tesla', model: 'Model S'}];

const tableRows = data.map((item, index) =>
<tr key={index}><td>{item.brand}</td><td>{item.model}</td></tr>
);

return (
<div>
<table><tbody>{tableRows}</tbody></table>
</div>
);
};

export default MyList;

The following screenshot shows what the component looks like when it is rendered:

Now, you should see the data in the HTML table.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.17.50