Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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

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!

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?