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.

1
  • 1
    map in React code is no different to map anywhere else. Docs apply everywhere. Commented Dec 23, 2016 at 0:46

1 Answer 1

6

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

messages.map((item, index) => {
   <li key={index}>{item}</li>
})
Sign up to request clarification or add additional context in comments.

4 Comments

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 Why? (Genuinely curious)
@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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.