2

In my React component, I want to use the map function to display some messages that come in an array. The array is very simple, just the messages:

const messages = [
   "John called and left a message.",
   "Marketing report is ready!",
   "Today's sales meeting is cancelled."
]

I don't want to complicate this array anymore than necessary so there's no id for these messages.

When I try to use the map function in my React component, it wants me to have a unique key/id for each item. How do I use the index for each item in this array?

I tried this code

<ul>
{messages.map(item => {
   <li key={item.index}>{item}</li>
})}
</ul>

but getting an error message that reads:

Each child in an array or iterator should have a unique "key" prop.

Sam
  • 26,817
  • 58
  • 206
  • 383
  • 1
    `map` in React code is no different to `map` anywhere else. [Docs apply everywhere](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). – Dan Prince Dec 23 '16 at 00:46

1 Answers1

6

Have not used React, though appears you can pass index of .map(callback)

messages.map((item, index) => {
   <li key={index}>{item}</li>
})
guest271314
  • 1
  • 15
  • 104
  • 177
  • This is how you'd do it. Additionally, I'd preface the index with the type of items you're iterating over. Something like `key={\`message-${index}\`}`. – Jecoms Dec 23 '16 at 00:46
  • @Jecoms Why? (Genuinely curious) – Dan Prince Dec 23 '16 at 00:48
  • @DanPrince More of a personal preference while developing/debugging to be more declarative. Ideally, you should use unique ids for the iterated items as the array index has no functional dependency on the item it holds. – Jecoms Dec 23 '16 at 00:57
  • I feel like the name you give your key has minimal value compared to the name you give the component itself when debugging. Ideally, you want to use an id which _is_ specific to the item, rather than the index, so that you don't do extra work when you sort/shuffle lists. – Dan Prince Dec 23 '16 at 01:01