Lists and Keys in React
Learn how to render lists and the importance of keys in React applications.
1. Rendering Lists in React
Rendering a list in React is done by mapping over an array of data and returning a React element for each item in the array.
function NameList() { const names = ['Alice', 'Bob', 'Charlie']; return (
-
{names.map((name, index) => (
- {name} ))}
Explanation: The map
function iterates over the names
array and generates a list item for each name.
2. Importance of Keys
Keys are a crucial part of rendering lists in React. They help React identify which elements have changed, are added, or are removed.
Rules for Keys:
- Keys must be unique among siblings.
- Do not use indices as keys if the list can change dynamically.
Example with unique keys:
function NameList() { const people = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' } ]; return (
-
{people.map(person => (
- {person.name} ))}
Explanation: Here, person.id
is used as the key because it is unique and stable.
3. Rendering Complex Lists
You can render more complex lists by including additional details about each item:
function UserProfileList() { const users = [ { id: 1, name: 'Alice', age: 25 }, { id: 2, name: 'Bob', age: 30 }, { id: 3, name: 'Charlie', age: 35 } ]; return ({users.map(user => (); }))}{user.name}
Age: {user.age}
Explanation: Each user’s profile is rendered using their id
as a key and their details are displayed in the UI.
4. Handling Dynamic Lists
For lists that change dynamically (e.g., adding or removing items), ensure keys remain consistent:
function DynamicList() { const [items, setItems] = React.useState([ { id: 1, value: 'First Item' }, { id: 2, value: 'Second Item' } ]); const addItem = () => { const newItem = { id: items.length + 1, value: `Item ${items.length + 1}` }; setItems([...items, newItem]); }; return (); }{items.map(item => (
- {item.value}
))}
Explanation: The addItem
function appends a new item to the list while maintaining unique keys.
5. Best Practices
- Always use unique and stable keys to improve rendering performance.
- Avoid using array indices as keys for dynamic lists.
- Structure your data in a way that ensures the availability of unique identifiers.