Home > Blockchain >  How to give non-changing unique key to siblings in React
How to give non-changing unique key to siblings in React

Time:04-19

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.

CodePudding user response:

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).

CodePudding user response:

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} />
  ))}
  • Related