Lists and Keys in React.js
1. Rendering Lists in React
In React, you can render a list of items using the map() method, which is a standard JavaScript function that transforms arrays. You can iterate over the array and return JSX for each item.
Example:
function NumberList(props) {
const numbers = props.numbers;
return (
{numbers.map((number) => (
- {number}
))}
);
}
const numbers = [1, 2, 3, 4, 5];
ReactDOM.render( , document.getElementById('root'));
In this example:
numbers
array is passed as a prop to the NumberList
component.map()
is used to create a list of <li>
elements based on the array.<li>
element.
2. The Importance of Keys
When rendering lists in React, each item should have a unique key. This helps React identify which items have changed, been added, or removed, which optimizes the rendering process. Without keys, React may render items inefficiently, resulting in performance issues or unexpected behavior
Why Are Keys Important?
Example with Keys:
function NumberList(props) {
const numbers = props.numbers;
return (
{numbers.map((number) => (
- {number}
))}
);
}
In this example, we added key={number.toString()}
to each <li>
element. The key must be unique among sibling elements.
3. Rules for Using Keys
key={index}
) because they can lead to issues when the list is modified. It’s better to use a unique identifier (like an id
) if available.Example with Objects:
If you have an array of objects, use a property (like id
) that is unique for each item in the array.
function UserList(props) {
const users = props.users;
return (
{users.map((user) => (
- {user.name}
))}
);
}
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Doe' }
];
ReactDOM.render( , document.getElementById('root'));
In this case, key={user.id}
ensures that each list item has a unique and stable key based on the id
property of the user
object.
4. Keys and Component State
Keys are especially important when components maintain their own state. React uses the key to understand which item should preserve its state during updates
Example:
function TaskList(props) {
const tasks = props.tasks;
return (
{tasks.map((task) => (
))}
);
}
function Task({ task }) {
const [isCompleted, setCompleted] = React.useState(false);
return (
setCompleted(!isCompleted)}>
{task.name} {isCompleted ? "(Completed)" : "(Pending)"}
);
}
In this example:
Task
component has its own state (isCompleted
).key={task.id}
, React ensures that the state of each task is preserved even if the list is re-rendered.
Conclusion
map()
method.Understanding and effectively using lists and keys in React will help you build dynamic and performant UIs.