Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda