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 with 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:

class App extends React.Component {
render() {
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>
);
}
}

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. The idea is the same as 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 code:

class App extends Component {
render() {
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>
);
}
}

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

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

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