Skip to content
Advertisement

React “Warning: Encountered two children with the same key”

I have a React app that mapping cards and each card have unique id although I’m getting error in console that some are not unique:

Warning: Encountered two children with the same key, 2294264. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.

Here is the code for building my card structure:

JavaScript

And here is the code for mapping the cards:

JavaScript

Can you please help me?

Advertisement

Answer

When you render a list of components with map(), each component should have a unique key property. It is for React to distinguish them.

Rendering a todo list, for example:

JavaScript

What you did wrong is that you added the key inside the component, where it should be when rendering inside map(), like so:

JavaScript

Notice that key = {index}. This would work, but it’s better to use a custom id if you have one. You can use key = {v._source.newsid} if v._source.newsid is a unique field.

For more visit keys section on the official documentation.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement