react-optimized-image
react-optimized-image copied to clipboard
"Encountered two children with the same key"
I'm getting console errors regarding duplicate keys when using the Img.
This is the code I'm using:
<Img
src={require('./img1.jpg')}
type="landingpageProject"
className={styles.image}
data-scroll
data-scroll-speed="-2"
/>
<Img
src={require('./img2.jpg')}
type="landingpageProject"
className={styles.image}
data-scroll
data-scroll-speed="-2"
/>
Which results in:
react_devtools_backend.js:2273 Warning: Encountered two children with the same key,
image/webp/1200. 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 behavior is unsupported and could change in a future version. in picture (created by Img) in Img (at projects/index.tsx:62) in div (at projects/index.tsx:61)
I've tried to set custom key properties on each of the Images with no luck.
Same thing happens to me, though it seems only when I use sizes/breakpoints
That's because you are using the same size multiple times. Currently the size is used as key for sources.
So
<Img src="..." sizes=[250, 500, 250] breakpoints=[...]/>`
will render as
<picture>
<source key={imageFormat + '250'} srcSet="..." media="..."/>
<source key={imageFormat + '500'} srcSet="..." media="..."/>
<source key={imageFormat + '250'} srcSet="..." media="..."/>
<img src="..."/>
</picture>
Make sure you don't repeat values in sizes and the error should go away.
I created a pull request for an unrelated issue and i also fixed this https://github.com/cyrilwanner/react-optimized-image/pull/12. But for now i'm waiting for a response.