Home > database >  React Keys - unique in that List or unique in the whole page?
React Keys - unique in that List or unique in the whole page?

Time:12-11

So I have multiple lists on the same page, with the same IDs from the database.

I got the error with "Each element needs a unique key"

I've research about this topic for a bit but I didn't quite understand:

Does the key need to be unique in that list, or in the whole pages' lists?

Let's say:

id=['guid1', 'guid2', 'guid3']

component render:

<ul className="list1">
 id.map((el) => <li key={el}>test</li>);
</ul>

<ul className="list2">
 id.map((el) => <li key={el}>test</li>);
</ul>

Would this be okay?

Thanks.

CodePudding user response:

Add a different prefix for each list

<ul className="list1">
   {id.map((el) => <li key={`first-${el}`}>test</li>)}
</ul>

<ul className="list2">
   {id.map((el) => <li key={`second-${el}`}>test</li>)}
</ul>

CodePudding user response:

const id=['guid1', 'guid2', 'guid3']
<ul className="list1">
{
id.map((idx,item) => <li key={idx}>{item}</li>)}</ul>
}
<ul className="list2">
{
 id.map((idx,item) => <li key={idx}>{item}</li>)
}
</ul>
You can generate index of every element of the array and use it as a key like this. Keys help React identify which items have changed, are added, or are removed. It is a best practice to provide keys.
Keys have to be unique for every element you can use entire element as keys.
A “key” is a special string attribute you need to include when creating
 lists of elements in React. Keys are used in React to identify which items
 in the list are changed, updated, or deleted. In other words, we can say 
that keys are used to give an identity to the elements in the lists.
React uses the key prop create a relationship between the component and the
 DOM element. The library uses this relationship to determine whether or not
 the component should be re-rendered. It is not recommended to use the index
 of the array as the key prop if you know the array will not be static.
In easy words keys are like your Identity which is yours only. Unique. 
Two elements cannot share the same key. They may have same name but the key
 will act as the separator between the two.
Array.map() method is a callback function. So it has its own local scope.
If you do two or more Array.map() for the same array as stated above, it will not have 
any effect on another. As all the keys will remain in their own lexical environment.
Keys will be unique in their own list

CodePudding user response:

The keys only have to be unique within the same parent element. The following is valid:

<div>
  {[1, 2].map(key => <p key={key} />}
</div>
<div>
  {[1, 2].map(key => <p key={key} />}
</div>

While the following isn't:

<div>
  {[1, 2].map(key => <p key={key} />}
  {[1, 2].map(key => <p key={key} />}
</div>
  • Related