2

I have used index key but it's still showing errors. Also tried with unique id from JSON data but can't solve this.

ERROR

Warning: Each child in a list should have a unique "key" prop.

const faqdata = this.props.faqData.map((faq, index) => (
    <li key={index}>
            {faq.description}
    </li>
));
veben
  • 19,637
  • 14
  • 60
  • 80
Kane
  • 605
  • 2
  • 8
  • 22
  • 2
    Possible duplicate of [Understanding unique keys for array children in React.js](https://stackoverflow.com/questions/28329382/understanding-unique-keys-for-array-children-in-react-js) and [error: Do not use Array index in keys](https://stackoverflow.com/questions/46735483) – adiga Feb 11 '19 at 07:26

3 Answers3

1

Warning: Each child in a list should have a unique "key" prop.

You will get this warning only when two or more items in the list have been supplied with the same key, Your code looks fine for me, it shouldn't be giving this warning, please try with a console.log(index) inside the map.

const faqdata = this.props.faqData.map((faq, index) => {
    console.log(index);
    <li key={index}>
            {faq.description}
    </li>
});

Anti Pattern:

You should not be using index of the map for you Key, its an antipattern, it may lead to unpredictable results.

Please check this https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318

You should be using proper unique-id for your Key, like a DB id or some unique-id.

This Key is used internally to identify the DOM elements to render and not to render again.

Praveen Rao Chavan.G
  • 2,772
  • 3
  • 22
  • 33
0

You must use ID, non duplicate name (or whatever unique you call it) but its index, because it compares the VDOM by its key:value pairs

Alexey Nikonov
  • 4,958
  • 5
  • 39
  • 66
0

In retrospect to other answers quoting that you should not use array index as a key, as much as it is an antipattern, it will still resolve the warning.

What you're doing is right and should remove the warning. Although I suspect the warning is coming when you iterate again over the result of your faqdata.

Every time you render something from an array, each entry should have the key attribute.

Dinesh Pandiyan
  • 5,814
  • 2
  • 30
  • 49