Lists and Keys
In React, when working with dynamic data, such as an array of items, we often need to render a list of items. The map
function in JavaScript is commonly used to transform an array of data into a new array of elements.
In the example code above, we have an array players
that contains the names of basketball players. We want to render a list of these players in our React component.
We can achieve this by using the map
function on the players
array. Inside the map
function, we define a callback function that takes each player and its index as arguments. We then return a new li
element for each player, setting the key
attribute to the index.
By assigning a unique key
to each li
element, React can efficiently update and reorder the list when changes occur.
Finally, we render the resulting playerList
array by wrapping it inside a ul
(unordered list) element.
By using the map
function and assigning a key
to each list item, we can dynamically render a list of items in React.
xxxxxxxxxx
// Let's say we have an array of players
const players = ['Kobe Bryant', 'LeBron James', 'Michael Jordan'];
// We can render the list of players using the map function
const playerList = players.map((player, index) => (
<li key={index}>{player}</li>
));
// Render the player list
return (
<ul>{playerList}</ul>
);