CodexBloom - Programming Q&A Platform

Next.js Image Component implementation guide on Route Change with Static Imports

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
next.js image react javascript

I tried several approaches but none seem to work. I'm stuck on something that should probably be simple. I'm experiencing an scenario where the Next.js Image component does not update the image displayed when I navigate between routes that use static imports for images. For example, I have two pages, `PageA` and `PageB`, each displaying a different image imported statically. When I navigate from `PageA` to `PageB`, the image from `PageA` remains visible instead of updating to the one associated with `PageB`. I’ve tried forcing a re-render by utilizing the `key` prop on the Image component to ensure it updates on route change: ```javascript // PageA.js import Image from 'next/image'; import imgA from '../public/imageA.png'; const PageA = () => { return <Image src={imgA} alt='Image A' width={500} height={300} key='PageA' />; }; export default PageA; ``` ```javascript // PageB.js import Image from 'next/image'; import imgB from '../public/imageB.png'; const PageB = () => { return <Image src={imgB} alt='Image B' width={500} height={300} key='PageB' />; }; export default PageB; ``` Despite this, the image still doesn’t change on navigation, and I see the following warning in the console: "Warning: Encountered two children with the same key, `PageA`. Keys should be unique." I've also checked that both images are correctly imported and exist in the `public` folder. My Next.js version is 13.0.0. How can I get the image to update correctly when switching between these pages? My development environment is Ubuntu. What's the best practice here? This is part of a larger CLI tool I'm building. What am I doing wrong? For context: I'm using Javascript on macOS. I'd really appreciate any guidance on this.