javascript / beginner
Snippet
Transforming Object Arrays into JSX Elements with Array Map
In React, you can convert JavaScript arrays into UI elements using the built-in .map() method. Each generated element requires a unique 'key' attribute to help React track and update list items efficiently.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const userList = [{ id: 1, name: 'Alice' },{ id: 2, name: 'Bob' }];export function UserNames() {return (<ul>{userList.map((user) => (<li key={user.id}>{user.name}</li>))}</ul>);}
react
Breakdown
1
const userList = [ ... ];
Defines an array of objects containing user data.
2
{userList.map((user) => (
Iterates through the array and maps each user object into a JSX element.
3
<li key={user.id}>{user.name}</li>
Returns a list item element with a unique key prop using the user's ID.