Reputation: 291
I am trying to show images from the API calls. I want to show a placeholder image in case there are no images or any errors. For that, I wrote this code,
const [errorImage, setErrorImage] = useState(null);
<Image
src={`${imageUrl}/${item.image}`}
alt="image"
layout="fill"
objectFit="contain"
onError={(e) => {
if (!errorImage) {
setErrorImage(true);
e.target.src = "/static/placeholder.jpg";
}
}}
But it's not working.
Upvotes: 1
Views: 5025
Reputation: 46
Changing the state of errorImage
when you set it to true
will cause the components to re-render, so you don't need to set e.target.src
directly.
Option 1 Instead, you can do the following:
const [errorImage, setErrorImage] = useState(null);
const errorImageUrl = "/static/placeholder.jpg";
const url = errorImage ? errorImageUrl : `${imageUrl}/${item.image}`;
<Image
src={url}
alt="image"
layout="fill"
objectFit="contain"
onError={(e) => {
if (!errorImage) {
setErrorImage(true);
}
}}
Option 2
Alternatively, you can use the new placeholder
prop that was added to <Image>
component in NextJS 11. This will show a blurry version of the image you provide.
<Image
src={url}
alt="image"
layout="fill"
placeholder="/static/placeholder.jpg"
objectFit="contain"
Upvotes: 3