Rendering Lists in React
When building a React application, you often need to render lists of components. Rendering lists allows you to dynamically display multiple items in the UI, such as a list of products, comments, or users.
To render a list in React, you can use the map
method to iterate over an array and return a new array of React elements. Each element represents an item in the list.
Here's an example of rendering a list of NBA players:
1const players = ['LeBron James', 'Stephen Curry', 'Kevin Durant'];
2
3function App() {
4 return (
5 <div>
6 <h1>NBA Players</h1>
7 <ul>
8 {players.map((player, index) => (
9 <li key={index}>{player}</li>
10 ))}
11 </ul>
12 </div>
13 );
14}
15
16ReactDOM.render(
17 <App />,
18 document.getElementById('root')
19);
In the above example, we have an array of NBA players. The map
method is used to iterate over each player and return a <li>
element for each player. The key
attribute is crucial to provide a unique identifier for each item in the list.
Keys help React identify which items have changed, been added, or been removed. It enables efficient rerendering and improves performance. It's important to use a unique identifier for the key
, such as an id
or index.
When rendering lists in React, remember to include a unique key
for each item. This ensures efficient updates and improves the overall performance of your React application.
xxxxxxxxxx
const players = ['LeBron James', 'Stephen Curry', 'Kevin Durant'];
function App() {
return (
<div>
<h1>NBA Players</h1>
<ul>
{players.map((player, index) => (
<li key={index}>{player}</li>
))}
</ul>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);