1

While looking through our code base, I found code that looks a bit like this:

const Carousel = ({ items }) => {
  return (
    <CarouselOuter>
      {items.map((item) => (
        <CarouselItemWrapper>
          <CarouselItem key={item.key}>
            ...
          </CarouselItem>
        </CarouselItemWrapper>
      )}
    </CarouselOuter>
  );
}

Notice that the key prop is on CarouselItem, not CarouselItemWrapper, the component that's directly returned from items.map. This seems to work fine, and there are no warnings in the console, but it runs counter to every example I've seen using map in React.

I want know if there's a good argument (specifically in regards to performance) for rearranging the code with the key as shown below, or if this is just a stylistic choice:

const Carousel = ({ items }) => {
  return (
    <CarouselOuter>
      {items.map((item) => (
        <CarouselItemWrapper key={item.key}>
          <CarouselItem>
            ...
          </CarouselItem>
        </CarouselItemWrapper>
      )}
    </CarouselOuter>
  );
}

Side note: CarouselOuter, CarouselItem, and CarouselItemWrapper are all , but I doubt that's relevant.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • 1
    The key attribute needs to be on the direct child, I tested myself and i get a warning if i put the key on the second level child. I found this subject who might answer your question : https://stackoverflow.com/questions/50303465/does-react-handle-keys-automatically-when-using-react-children-map – Zerowiel Mar 29 '21 at 21:54
  • You can check what key are set to each child by check the react dev tool :) I found this in the react code base, might interest you https://github.com/facebook/react/blob/6565795377d1d2c79a7708766f1af9e1a87517de/packages/react/src/ReactChildren.js – Zerowiel Mar 29 '21 at 22:00
  • @Zerowiel Actually, you're right. There is a warning, we just missed it earlier. Thank you for the links. – p.s.w.g Mar 29 '21 at 22:16
  • i was curious about your question that's why i tested it myself and found some edge case in the github i linked to you. If you use children.map there is no warning if you don't use key :p – Zerowiel Mar 29 '21 at 22:18

0 Answers0