Home >Web Front-end >JS Tutorial >React Lists and Keys
In React, lists and keys are essential concepts for rendering collections of elements efficiently and maintaining their identity across re-renders. Here’s a concise overview:
When you need to render multiple items, you typically map over an array to create a list of components. Here's a basic example:
const fruits = ['Apple', 'Banana', 'Cherry']; function FruitList() { return ( <ul> {fruits.map((fruit) => ( <li key={fruit}>{fruit}</li> ))} </ul> ); }
Keys help React identify which items have changed, been added, or removed. They should be unique among siblings but do not need to be globally unique. Keys should be stable, meaning they should not change between renders. A common practice is to use a unique identifier from your data, such as an ID:
const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }, ]; function UserList() { return ( <ul> {users.map((user) => ( <li key={user.id}>{user.name}</li> ))} </ul> ); }
By following these guidelines, you can create efficient, dynamic lists in your React applications!
The above is the detailed content of React Lists and Keys. For more information, please follow other related articles on the PHP Chinese website!