Search code examples
arraysreactjsfunctionloopsunique-key

How to make each child in a list should have a unique "key" prop in React


Gather data →

    const gatherComps = (data) => {
        let competencyList = []
        let i = 1
        while (i < 6) {
          if (data && data.hasOwnProperty(`competency${i}`)) {
            competencyList.push(data[`competency${i}`])
          }
          i++
        }
        return competencyList
      }

Prep Data →

    const displayInfo = (singleCC, i) => {
        const result = singleCC.length
          ? singleCC.map((cc, ind) => {
              return ind < 1 ? (
                <div className="competencyHeadline">
                  <b>{cc}</b>
                </div>
              ) : (
                <div className="competencyDesc" key={ind}>
                  <i>{cc}</i>
                </div>
              )
            })
          : ""
        return (
          <div key={i}>
            <>{result}</>
          </div>
        )
      }

Return Data →

    <div className="Competencies">
        <div className="wrapper">
            {gatherComps(data).map((cc, i) => displayInfo(cc, i))}
        </div>
    </div>

I've tried: key={i} key={`custom-name-title-` + i.toString()} key={ind} key={`custom-name-desc-` + ind.toString()} and some other simular things and can't get this warning to go away.

I've even included the same values for an id={} to make sure it continued to render a unique id, which it does, but I still get the warning...


Solution

  • You are missing key value for <div className="competencyHeadline">. You have that one at first iteration of .map.

    Just add custom key the same way you did:

    const displayInfo = (singleCC, i) => {
      const result = singleCC.length
        ? singleCC.map((cc, ind) => {
            return ind < 1 ? (
              <div className="competencyHeadline" key={ind}> <------------ HERE
                <b>{cc}</b>
              </div>
            ) : (
              <div className="competencyDesc" key={ind}>
                <i>{cc}</i>
              </div>
            );
          })
        : '';
      return (
        <div key={i}>
          <>{result}</>
        </div>
      );
    };