I’m using uuid for providing unique Ids, but I still get this warning:
Each child in a list should have a unique "key" prop.
function NavBar () {
return(
<ul className='nav justify-content-center'>
<Link /*to={item.ref}*/ className="nav-link">
<li className="nav-item" key={uuid()}> Home </li>
</Link>
{
navItems?.map((item) => {
return(
<>
<span className="listStyle"></span>
<Link to={item.ref} className="nav-link">
<li className="nav-item" key={uuid()}> {item.name} </li>
</Link>
</>
)
})
}
</ul>
);
}
2
Answers
You should add the key to the outermost element.
Few issues here.
Firstly it should be attached to the outermost element.
Secondly the point of a
key
is to be stable across renders – this tells React not to remount / recreate the component and instead just to re-render it. (Big performance improvement). You should use something static, such asitem.ref
. This is because otherwise (as we’re regenerating the items based on the list on every render) React has no way to track them every time it updates the component, this helps resolve that.For example: