I have this React
code:
export default function Technologies({ technologies }) {
return (
<>
{ Object.keys(technologies).map((key, i) => (
<span>
<span className={styles.post}><h3 className={'bold300'}>{key}</h3></span>
<div className={styles.techList}>
<ul key={i}>
{ Object.keys(technologies[key]).map((key2, idx) => (
<li key={idx}>{key2}
{ technologies[key][key2].map(key3 => (
<span key={key3.name} className={styles.badge}><Image src={key3.name} width={key3.w} height={key3.h} /></span>
)) }
</li>
)) }
</ul>
</div>
</span>
)) }
</>
)
}
Here you can see nested iteration, and everywhere I use i
or idx
to create unique key for list, but still keep getting warning for this string:
...
<ul key={i}>
...
As I said, I know what this error means, and even know how to fix, but not in this case, I just don't know, where I should put key
to prevent this warning. Thanks!
CodePudding user response:
The key
should be present on the root element. So, the first key
should be on the span
and not on the ul
.
export default function Technologies({ technologies }) {
return (
<>
{Object.keys(technologies).map((key, i) => (
<span key={i}>
<span className={styles.post}>
<h3 className={"bold300"}>{key}</h3>
</span>
<div className={styles.techList}>
<ul>
{Object.keys(technologies[key]).map((key2, idx) => (
<li key={idx}>
{key2}
{technologies[key][key2].map((key3) => (
<span key={key3.name} className={styles.badge}>
<Image src={key3.name} width={key3.w} height={key3.h} />
</span>
))}
</li>
))}
</ul>
</div>
</span>
))}
</>
);
}