I have a header navigation component that renders navigation from two parts of a JSON response.
The navigation renders correctly but I am getting the: 'Each child in a list should have a unique "key" prop error' even though from what I can see I do have a key for each child element.
The Id from both map calls will be completely unique.
This is the complete code for the component so far:
import React, { useContext } from 'react';
import { Link } from "react-router-dom";
import { HeaderContext } from '../context/headerContext';
const renderToplevelPages = (toplevelPages) => {
return toplevelPages.map(({ PageUrl, NavLinkText, Id, SubNavMenuItems }) => (
<li key={Id}><Link to={PageUrl}>{NavLinkText}</Link>
{SubNavMenuItems && <ul>{renderToplevelPages(SubNavMenuItems)}</ul>}
</li>
));
};
function Header() {
const headerData = useContext(HeaderContext);
return (
<nav>
<Link to="/">Logo here</Link>
{headerData
? <ul>
<li>
<Link to={headerData.Menu.PageUrl}>Menu</Link>
<ul>
{headerData.Menu.Categories.map(categoryItem => (
<li key={categoryItem.Id}><Link to={categoryItem.CategoryUrl}>{categoryItem.CategoryName}</Link></li>
))}
</ul>
</li>
<li>
<a className="navbar-icon fa-user snipcart-customer-signin">Login/Register</a>
</li>
{renderToplevelPages(headerData.TopLevelPages)}
</ul>
: <div></div>
}
</nav >
)
}
export default Header;
CodePudding user response:
You're missing a key
here:
<li>
<Link to={headerData.Menu.PageUrl}>Menu</Link>
....
</li>
and here:
<li>
<a className="navbar-icon fa-user snipcart-customer-signin">Login/Register</a>
</li>
Just because they're not part of a call to Array.map
, they're still children of the parent <ul>
so they need a key
.
If that doesn't fix it, perhaps your Id
s aren't correct - I suggest you check them by rendering the Id instead of e.g. CategoryName
.