Lists and Keys
In React 19, rendering lists is a common requirement for many applications. When rendering lists, it’s essential to understand how to use keys to help React keep track of components. This documentation will guide you through the basics of rendering lists and keys in React 19.
Basic Example
To render a list in React, you can use the map() function to iterate over an array and return a JSX element for each item. Here’s a simple example:
import React from 'react';
function NumberList(props) {
const numbers = props.numbers;
return (
<ul>
{numbers.map((number) => (
<li key={number}>{number}</li>
))}
</ul>
);
}
const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
<NumberList numbers={numbers} />,
document.getElementById('root')
);In this example, we’re using the map() function to iterate over the numbers array and return a <li> element for each number. The key prop is set to the number value, which helps React keep track of the components.
Advanced Usage
When dealing with more complex data structures, you may need to use a combination of map() and nested JSX elements. Here’s an example:
import React from 'react';
function TodoList(props) {
const todos = props.todos;
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>
<span>{todo.text}</span>
<button onClick={() => handleDelete(todo.id)}>Delete</button>
</li>
))}
</ul>
);
}
const todos = [
{ id: 1, text: 'Buy milk' },
{ id: 2, text: 'Walk the dog' },
{ id: 3, text: 'Do homework' },
];
function handleDelete(id) {
console.log(`Deleted todo with id ${id}`);
}
ReactDOM.render(
<TodoList todos={todos} />,
document.getElementById('root')
);In this example, we’re using map() to iterate over the todos array and return a <li> element for each todo item. The key prop is set to the todo.id value, which helps React keep track of the components. We’re also using a nested <button> element with an onClick handler to handle deleting a todo item.
Best Practices
Here are some best practices to keep in mind when rendering lists and keys in React 19:
- Always use a unique
keyprop for each component in a list to help React keep track of components. - Use the
map()function to iterate over arrays and return JSX elements. - Avoid using the index of the array as the
keyprop, as this can cause issues when the array changes. - Use a combination of
map()and nested JSX elements to handle more complex data structures.
Key Takeaways
Here are the key takeaways from this documentation:
- Use the
keyprop to help React keep track of components in a list. - Use
map()to iterate over arrays and return JSX elements. - Always use a unique
keyprop for each component in a list. - Follow best practices to ensure efficient and effective rendering of lists in React 19.