â° Loops
How to render a collection of items in JSX
Array Map
The most common way to loop over a collection of data in React is to use the Array map
method. It takes a callback function that gets called on each element to transform the data into UI elements.
const data = [
{ id: 1, name: 'Fido đ' },
{ id: 2, name: 'Snowball đ' },
{ id: 3, name: 'Murph đââŦ' },
{ id: 4, name: 'Zelda đ' },
];
function ListOfAnimals() {
return (
<ul>
{data && // Only render if there's data - see 'Conditional Rendering'
data.map(({ id, name }) => {
return <li key={id}>{name}</li>;
})}
</ul>
);
}
Challenge
Define an array of animals called data. Use a .map()
to return a list of all the animals in the data array.