Lists and Keys
When working with React, it is common to render lists of components. You may have a list of items fetched from an API, a set of data from a database, or an array you define in your code. React provides a way to render dynamically generated lists using the map
function.
Rendering a List of Components
To render a list of components in React, you can use the map
function to iterate over an array of data and return a component for each item.
Here's an example of rendering a list of students:
1// Arrays of data
2const students = [
3 { id: 1, name: 'John' },
4 { id: 2, name: 'Jane' },
5 { id: 3, name: 'Bob' }
6];
7
8// Render a list of students
9const StudentList = () => {
10 return (
11 <ul>
12 {students.map(student => (
13 <li>{student.name}</li>
14 ))}
15 </ul>
16 );
17};
18
19ReactDOM.render(
20 <StudentList />,
21 document.getElementById('root')
22);
In the example above, we have an array of students with their respective names. We use the map
function to iterate over the array and return an <li>
element for each student.
Adding Unique Keys
When rendering a list of components in React, it's important to provide a unique key
prop to each component. This helps React efficiently update and re-order the list when changes occur.
In the previous example, we can add a unique id
property to each student object and use it as the key
prop for the <li>
element:
1{students.map(student => (
2 <li key={student.id}>{student.name}</li>
3))}
By providing a unique key
prop, React can track each component and optimize the rendering process.
When using the map
function to render a list, remember to include a key
prop for each component to improve performance and avoid potential issues.
xxxxxxxxxx
// Arrays of data
const students = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' }
];
// Render a list of students
const StudentList = () => {
return (
<ul>
{students.map(student => (
<li key={student.id}>{student.name}</li>
))}
</ul>
);
};
ReactDOM.render(
<StudentList />,
document.getElementById('root')
);