简体   繁体   中英

How to show a placeholder image in nextjs image component

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM