reactjskeywarnings

How can I fix the 'Each child in a list should have a unique 'key' prop' warning in React?


I am developing a react app and I am unable to fix this warning can you please help locate where specifically I need a key

Here, is my code block where the error is generated:

const [experiences, setExperiences] = useState([]);
useEffect(() => {
  const query = '*[_type == "experiences"]';
  const skillsQuery = '*[_type == "skills"]';

  client.fetch(query).then((data) => {
    setExperiences(data);
  });

  client.fetch(skillsQuery).then((data) => {
    setSkills(data);
  });
}, []);

<div className="app__skills-exp">
  {experiences.map((experience) => (
    <motion.div className="app__skills-exp-item" key={experience.year}>
      <div className="app__skills-exp-year">
        <p className="bold-text">{experience.year}</p>
      </div>
      <motion.div className="app__skills-exp-works" key={experience.works}>
        {experience.works.map((work) => (
          <>
            <motion.div
              whileInView={{ opacity: [0, 1] }}
              transition={{ duration: 0.5 }}
              className="app__skills-exp-work"
              data-tip
              // data-for is deprecated as v4 using data-tooltip-id instead
              data-tooltip-id={work.name}
              key={work.name}
            >
              <h4 className="bold-text">{work.name}</h4>
              <p className="p-text">{work.company}</p>
            </motion.div>
            <Tooltip
              id={work.name}
              effect="solid"
              arrowColor="#fff"
              className="skills-tooltip"
            >
              {work.desc}
            </Tooltip>
          </>
        ))}
      </motion.div>
    </motion.div>
  ))}
</div>;

I have tried using key in tooltip but that didnt work


Solution

  • Every elements of a list should have a key prop.

    So when you do this :

    {experience.works.map((work) => (
      <>
        <motion.div
          whileInView={{ opacity: [0, 1] }}
          transition={{ duration: 0.5 }}
          className="app__skills-exp-work"
        // ...
      </>
    ))}
    

    The component you use is called a Fragment, the <></> is a shortcut to write it, ant it cannot contains a key prop written that way.

    It is common to use the shortcut instead of the full name, but in that specific case you should write it like this:

    {experience.works.map((work) => (
      <Fragment key={work.name}>
        <motion.div
          whileInView={{ opacity: [0, 1] }}
          transition={{ duration: 0.5 }}
          className="app__skills-exp-work"
         // ...
      </Fragment>
    ))}