Warning: Encountered two children with the same key, ``

170 Views Asked by At

I am using ReactJS, NextJS 14, Tailwind CSS and Framer Motion.

I have to put unique keys for each repeated child in React, so I do have to in NextJS. That is also why I put the index value to the children as their key, because the index value will be unique, increasing by one for every single element of the array. However, the warning keeps saying that I put nothing. I could not understand, so: I logged that value in the console, which showed me expected numbers (0, 1, 2...); changed that value into one of the properties of linkInfo, which is unique; and I even tried to put the Date.now() there. All of them showed me the expected unique values, but the warning was the same:

Warning: Encountered two children with the same key, ``. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behaviour is unsupported and could change in a future version.

This is the code that makes that problem. When I removed this code, the problem disappeared.

{menuFocusLevel === 2 && (
  <motion.div
    initial={{ opacity: 0, x: -10 }}
    animate={{ opacity: 1, x: 0 }}
    exit={{ opacity: 0, x: 10 }}
    transition={{ duration: 0.16, type: "spring" }}
    className="absolute top-7 -right-1 bg-black w-48 border border-red flex flex-col py-0.5 rounded-l-sm rounded-br-sm"
  >
    {links.map((linkInfo, menuLinkIdx) => (
        <MemoriesLink key={menuLinkIdx} {...linkInfo} isInMenu />
    ))}
  </motion.div>
)}

I tried to add repeated children, and I was expecting them not to make any errors about the keys.

1

There are 1 best solutions below

0
Cattynip On

My problem was with Framer Motion. I wrapped that code with <AnimatePresence />. But inside of that tag there were two <motion.div /> tags, which caused the problem with the keys. After separating two components in each <AnimatePresence /> tag the warning was gone.