How to use dynamic link in next js Image?

Article Tarif Hossain

Next Image is a first-class component supported in Next.js. It unlocks some easy-to-use image management features like image optimization and responsive sizing. Next Image work similarly to the Html img tag. For the dynamic use case, we should fetch dynamic data to the page. Fetch the dynamic data we should use the getServerSideProps or getStaticProps to pass the dynamic prop.

Example :

import Image from "next/image";

export const WithDynamicImage = ({imageDynamic}) => {

return (
    <Image src={imageDynamic}
      alt="Picture of the author"
      width={500}
      height={500}
    />
)

}

export async function getServerSideProps({
  params,
}) {
  const image = await getImages() // fetch your data;
  const imageDynamic = image[param.id] //pass the prop from the url

  return { props: { imageDynamic : imageDynamic || null } };
}

Line no 6 we are using {imageDynamic} as props to get a dynamic image source link.