Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Each child in a list should have a unique "key" prop while nested list iteration

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
      ))}
    </>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading