My console keep giving me this error
Warning: Each child in a list should have a unique "key" prop.
despite that I gave a unique key to my map list. My code looks like this:
const [cardItem, setCardItem] = useState(data);
const uniqueIds = [];
const uniqueCat = cardItem.filter((element) => {
const isDuplicate = uniqueIds.includes(element.category);
if (!isDuplicate) {
uniqueIds.push(element.category);
return true;
}
return false;
});
return (
<>
<div className="art-container">
{uniqueCat
.filter((id) => id.id < 73)
.map((item, i) => {
return item.category === "Filmmaking" ||
item.category === "Multimedia" ? (
<div key={i}>
<div className="art-projects-contants">
<h1>{item.category}</h1>
<Card cardItem={cardItem} cat={item.category} />
</div>
</div>
) : (
<>
<div key={i} className="art-img-projects-contants" >
<h1>{item.category}</h1>
<Img cardItem={cardItem} cat={item.category} />
</div>
</>
);
})}
</>
);
I tried to give it a key with the id by {item.id} also giving the second div a key but it still give me the same error. Could the problem be from the uniqueCat because it gave two arrays when I console log it as in the picture?
How can I fix the Unique key problem?
Note: I am using map function in other places in my project but its the only place I have this error.
CodePudding user response:
Your first div has a key, while your second does not:
<div className="art-container">
{uniqueCat
.filter((id) => id.id < 73)
.map((item, i) => {
return item.category === "Filmmaking" ||
item.category === "Multimedia" ? (
<div key={i}>
<div className="art-projects-contants">
<h1>{item.category}</h1>
<Card cardItem={cardItem} cat={item.category} />
</div>
</div>
) : (
<>
<div key={i} className="art-img-projects-contants" > // <== add key here
<h1>{item.category}</h1>
<Img cardItem={cardItem} cat={item.category} />
</div>
</>
);
})}
</div>
CodePudding user response:
The key
must be unique on every element in the component tree, your index (i
) may have already been used on a different element, avoid using just the loop index as the key.
It's best to use an actual id
from the filtered uniqueCat
because this id will most likely be unique from any other id
s.
Sample code
<div className="art-container">
{uniqueCat
.filter((id) => id.id < 73)
.map((item) => {
return item.category === 'Filmmaking' ||
item.category === 'Multimedia' ? (
<div key={item.id}>...</div>
) : (
<div key={item.id}>...</div>
);
})}
</div>;
If the id
s isn't very unique then you can do some form concatenation with template strings using the loop index.
Like this
<div className="art-container">
{uniqueCat
.filter((id) => id.id < 73)
.map((item, i) => {
return item.category === 'Filmmaking' ||
item.category === 'Multimedia' ? (
<div key={`{item.id}-${i}`}>...</div>
) : (
<div key={`{item.id}-${i}`}>...</div>
);
})}
</div>;