Auto assigning unique key to each child of a list in React

Amit Merchant · February 21, 2022 ·

If you have ever worked with lists in React, you might have rendered it using the Array.prototype.map() method like so.

export default function App() {
  const list = [
    { key: 1, value: 10 },
    { key: 2, value: 20 },
    { key: 3, value: 30 }
  ];

  return (
    <div>
    {list.map(({ key, value }) => (
        <div>{value}</div>
    ))}
    </div>
  );
}

Now, the problem with this is it will render the list successfully leaving a warning that looks like so.

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

This is because React uses a unique “key” prop on each child of the list to create a relationship between the component and the DOM. This is to ensure that react re-renders the child correctly next time. And so, it’s important to have a unique key assigned to every child of the list.

Manually assigning unique keys

The easy fix is to assign the “key” prop to the element like so.

{list.map(({ key, value }) => (
    <div key={key}>{value}</div>
))}

This will resolve the warning that was occurring previously since each child will now have a unique key.

Auto-assigning unique keys

But there’s a more elegant and recommended way to fix this and this is to use React.Children.toArray method.

So, if we were to write the previous example with this method, here’s how we can do it.

export default function App() {
  const list = [
    { key: 1, value: 10 },
    { key: 2, value: 20 },
    { key: 3, value: 30 }
  ];

  return (
    <div>
    {
        React.Children.toArray(
            list.map(({ key, value }) => <div>{value}</div>)
        )
    }
    </div>
  );
}

When rendering the list through the React.Children.toArray method, React will return the children opaque data structure as a flat array with keys assigned to each child.

And so, it’s not necessary to explicitly assign a unique key to each child. React will handle that for you gracefully!

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?