Mark As Completed Discussion

Lists and Keys

In React, working with lists is a common task when rendering dynamic content. With React, you can easily map over an array of data and generate a list of elements.

Let's say we have an array of numbers and we want to render each number as a list item:

SNIPPET
1import React from 'react';
2
3function NumberList() {
4  const numbers = [1, 2, 3, 4, 5];
5
6  return (
7    <ul>
8      {numbers.map((number) => (
9        <li key={number}>{number}</li>
10      ))}
11    </ul>
12  );
13}
14
15export default NumberList;

In this example, we define an array of numbers and use the map function to iterate over the array. We provide a key prop to each list item, which helps React identify each item in the list.

Adding a unique key to each item is important because it helps React efficiently update the list when items are added, removed, or rearranged. React uses the key prop to determine the identity of each component in the list.

When rendering a list of components, it's important to provide a unique key to each component. The key should be a unique identifier for each item, such as an ID from the database or a unique attribute in the data.

Using keys in lists improves performance and helps React efficiently update the UI. It's also important to note that keys should be stable and unique within the list. Avoid using the index of the array as the key, as it can cause issues when the order of the list items changes.

Now that you understand how to work with lists and add keys to components, try writing code to log numbers 1 to 10 to the console using a similar approach.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment