3

I need to render a list with string items like ['a', 'b', 'c', 'a'], the items are allowed to be duplicate to each other, what is the proper way to choose a react key in {list.map(x => <span key={?}>{x}</span>)}?

golopot
  • 10,726
  • 6
  • 37
  • 51
  • Does this answer your question? [When giving unique keys to components, is it okay to use Math.random() for generating those keys?](https://stackoverflow.com/questions/29808636/when-giving-unique-keys-to-components-is-it-okay-to-use-math-random-for-gener) – Victor Santizo Mar 24 '23 at 06:54

1 Answers1

3

This should work

{list.map((x,i) => <span key={`${x}-${i}`}>{x}</span>)}
samweke
  • 132
  • 9
  • Using indexes as key is a bad practice, ES Lint should complain if you have it enabled in your IDE. React documentation also states why it's a bad practice: https://react.dev/learn/rendering-lists#why-does-react-need-keys – Ramon Dias Aug 12 '23 at 00:21