Reputation: 149
i want to use dynamic link in next js Image
.
Next Js suggest
<Image
src="/me.png"
alt="Picture of the author"
width={500}
height={500}
/>
But i want to use like
const imageDynamic = [Image][1]
<Image
src="https://en.wikipedia.org/wiki/Image#/media/File:Image_created_with_a_mobile_phone.png" or {imageDynamic}
alt="Picture of the author"
width={500}
height={500}
/>
image will come from api so image src will change everytime. i can not use a link in next js Image , can it possbile to use a link in next js Image?
Upvotes: 4
Views: 23879
Reputation: 247
Next Image work similar like the html img
tag. For the dynamic use case you should fetch dynamic data to the page.
to fetch the dynamic data you should use the getServerSideProps
or getStaticProps
to pass the dynamic prop via url:
https://nextjs.org/docs/basic-features/data-fetching
import Image from "next/image";
const WithDynamicImage = ({image}) => {
return (
<Image src={image}
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: { image : imageDynamic || null } };
}
export default WithDynamicImage;
the data fetching only works in pages/
folder and do not work in components. If you would use into component you should fetch the data in a page and pass the prop into the component.
Upvotes: 6