Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda