Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
How to give non-changing unique key to siblings in React

I've been struggling for over an hour but couldn't find the solution.

The data structure is like

const arr = [
  { id: 1, title: 'something', tags: ['first', 'second', 'third'] },
  { id: 2, title: 'something', tags: ['first', 'second', 'third'] },
  { id: 3, title: 'something', tags: ['first', 'second', 'third'] },
];

And I wanna render Tag components for each item of arr using map function, like below.

const Item = ({ item }) => (
  <article>
    <h1>{item.title}</h1>
    <ul>
      {item.tags.map(tag => (
        <Tag key={?} tag={tag} />
      ))}
    </ul>
  </article>
);

But what can I use for key except the index in an array?

I tried Date.now() but it's not unique for sibling nodes, and I also tried Math.random() and it worked, but it will change every time Item re-renders. There are some libraries for this as far as I know but I heard they change too when re-rendering.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

But what can I use for key except the index in an array?

For the items (article instances), you'd use their id. (I assume those are unique in the array.)

For the tags, use the tag itself. (I'm inferring from the name "tag" that you don't have the same tag repeated in the same array.)

const Item = ({ item }) => (
  <article key={item.id}>
  {/*      ^^^^^^^^^^^^^ */}
    <h1>{item.title}</h1>
    <ul>
      {item.tags.map(tag => (
        <Tag key={tag} tag={tag} />
        {/*  ^^^^^^^^^ */}
      ))}
    </ul>
  </article>
);

Keys only have to be unique between siblings (e.g., elements in the array you're mapping), they don't have to be globally unique (documentation link).

about 4 years ago · Juan Pablo Isaza Report

0

hmmm someone suggested to use tag.id, I don't think that's a thing in your code. I think they meant arr.id, but to do that I think you'd need to do something along the lines of:

  {item.map((items, index) => (
    <Tag key={items.id} tag={items.tag} />
  ))}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!