a blog for those who code

Saturday, 18 August 2018

How to Fix Each child in an array or iterator should have a unique key prop in React.js

In this post we will see the solution of fixing "Each child in an array or iterator should have a unique key prop" in React.js. The error says that every child in a an array should have a unique key because React uses this key property for re-rendering.


Let's say you are dynamically creating children of an array and in this case you have to tell React that each child is different for React to know about it. Assigning 'key' property helps the React to keep the state and identity of each element maintained through multiple renders.

For Example, I have a tags array and I am creating a span element for each tag in teh array and adding it to another array as shown below.

tags.map(tag => {
    tagSpan = <span className="tag">{tag}</span>;
    tagsArray.push(tagSpan);
});

This code will likely throw an error "Each child in an array or iterator should have a unique key prop" because we have not given the key property to the span element and all the span has the same className i.e. "tag".

To fix we have to change our code  as shown below

tags.map(tag => {
    tagSpan = <span key={tag} className="tag">{tag}</span>;
    tagsArray.push(tagSpan);
});

Please like and share the CodingDefined.com blog if you find it useful and helpful.

2 comments:

  1. Spot on with this write-up, I really believe
    that this website needs a great deal more attention. I'll probably be
    back again to read more, thanks for the info!

    ReplyDelete
  2. I do agree with ɑll the ideas you've presented to yoᥙr post.

    Тhey are very convincing and will definitеly woгk.
    Nonetheless, the posts ɑre too short for starters. May jᥙst you
    pleaze extend them a llittle from next time?Thɑnks for the post.

    ReplyDelete