Photo by Gemma Evans on Unsplash

React

React List — Warning: Each child in a list should have a unique key props

Onur Dayıbaşı
Frontend Development With JS
2 min readDec 3, 2022

--

Most of the time, we face "Warning: Each child in a list should have a unique key prop" in the console, and the warning assists us to https://reactjs.org/docs/lists-and-keys.html#keys

The solution is easy; you must give keys to list elements. So Virtual DOM catches quickly lists updates, removes, and additions.

https://reactjs.org/docs/lists-and-keys.html#keys website you can see.

Below code

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number.toString()}> {number}
</li>
);

or

const todoItems = todos.map((todo) =>
<li key={todo.id}> {todo.text}
</li>
);

React framework wants unique ids. Sometimes we have different conditions because of UI frameworks. For example. MaterialUI, SemanticUI, PrimeReact, Ant, etc.. have some container components.

  • Breadcrumb compose → BreadcrumpSections
  • Menu → MenuItem
  • Accordion compose → AccordionTitle and AccordionContents
  • Tree compose → TreeNode

When using this kind of Component, you must be careful about the hierarchy

The below structure is correct, but you can build this kind of structure if your Breadcrumb Sections are static.

Breadcrumb Static Generation

If breadcrumb data comes dynamic from DB or LocalStorage, then you must map and generate JSX.

const breadcrumpItems = todos.map((todo) =>
<div>
<BreadcrumbSection> {todo.text} </BreadcrumbSection>
<BreadcrumbDivider> </BreadcrumbDivider>
</div>
);

This kind of definition has problems because its stylings are corrupted when you add div to the hierarchy.

In this situation, we can use Fragment <> to not affect style. It works; the stylings are not corrupted, but it continues to give warnings below.

Each child in a list should have a unique key props.

The Solution

The solution using React.Fragment with a unique key. If you give Fragment a key;

  • Your styling is not corrupted
  • Critical warnings will be removed.
<Breadcrumb>
{data.map((item, index) => {
return (
<React.Fragment key={_.uniqueId()}>
<Breadcrumb.Section>{item.text}</Breadcrumb.Section>
{index < data.length - 1 && <Breadcrumb.Divider />}
</React.Fragment>
);
})}
</Breadcrumb>

--

--