Skip to main content

Rendering Lists

Rendering Lists

The map method is a common and straightforward way to render lists in React. You can map over an array of data and create an array of JSX elements.

const items = [
{ id: 1, value: "Item 1" },
{ id: 2, value: "Item 2" },
{ id: 3, value: "Item 3" },
];

const itemList = items.map(({ id, value }) => <li key={id}>{value}</li>);

return <ul>{itemList}</ul>;

List items with Key

You need to give each array item a key — a string or a number that uniquely identifies it among other items in that array. Or else you would get an error in console as below,

Warning: Each child in a list should have a unique “key” prop.

Where to get your key

Different sources of data provide different sources of keys:

  1. Data from a database: If your data is coming from a database, you can use the database keys/IDs, which are unique by nature.
  2. Locally generated data: If your data is generated and persisted locally (e.g. notes in a note-taking app), use an incrementing counter, crypto.randomUUID() or a package like uuid when creating items.

Rules of keys

  1. Keys must be unique among siblings. However, it’s okay to use the same keys for JSX nodes in different arrays.
  2. Keys must not change or that defeats their purpose! Don’t generate them while rendering.

Why does React need keys?

Imagine that files on your desktop didn’t have names. Instead, you’d refer to them by their order — the first file, the second file, and so on. You could get used to it, but once you delete a file, it would get confusing. The second file would become the first file, the third file would be the second file, and so on.

File names in a folder and JSX keys in an array serve a similar purpose. They let us uniquely identify an item between its siblings. A well-chosen key provides more information than the position within the array. Even if the position changes due to reordering, the key lets React identify the item throughout its lifetime.

info

You might be tempted to use an item’s index in the array as its key. In fact, that’s what React will use if you don’t specify a key at all. But the order in which you render items will change over time if an item is inserted, deleted, or if the array gets reordered. Index as a key often leads to subtle and confusing bugs.