javascript / beginner
Snippet
Iterating and Rendering Collections with Array Map and Keys
In React, you transform arrays of data into lists of JSX elements using the standard array map method. Each generated element requires a unique 'key' prop to help React track additions, updates, and removals efficiently.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
function FruitList({ items }) {return (<ul>{items.map((fruit) => (<li key={fruit.id}>{fruit.name}</li>))}</ul>);}
react
Breakdown
1
function FruitList({ items }) {
Declares a React component accepting a prop containing an array of item objects.
2
{items.map((fruit) => (
Iterates over each fruit item in the array to return a new JSX element.
3
<li key={fruit.id}>{fruit.name}</li>
Renders a list item with a stable unique key identifier and displays the fruit name.