1

How can I set a default image for an img tag in case src link is invalid in react?

I've tried using onerror like so, but it doesn't seem to work.

Im using Next.js and hooks.

<img alt="Site Logo" src="/secondary.jpg" onerror="this.onerror=null; this.src='https://static.thenounproject.com/png/140281-200.png';" />

By invalid, I mean when the src receives a URL and it can't find an image I would like to make it display a default image.

When it can't find an image it will display this

enter image description here

Instead of this, I would like to make it display a default image if it can't find the image from the URL provided.

Usually, this can be done with onerror like above but it doesn't work in react for some reason, whats the alternative solution?

devAR
  • 349
  • 7
  • 21
  • What do you mean by `invalid in react`? Are you using JS to populate the link? Is this JS that could be null or undefined? – Tom Foster Oct 12 '21 at 20:04
  • I've updated the post to be more clear. Basically, I want it to display a default image if it cant find an image from the URL provided in the src. I am populating the link from an API and the link is different everytime but sometimes there wont be an image from the link. @TomTomTom – devAR Oct 12 '21 at 20:20
  • 1
    Does this answer your question: [What is the best way to have a fallback image in NextJS?](https://stackoverflow.com/a/66953317/1870780)? You can directly replace `next/image` with an `` element instead, if that's what you're using. – juliomalves Oct 12 '21 at 21:56

1 Answers1

1

I was facing this issue and couldn't find a working solution anywhere, but I was able to understand an easy one. You can simply do this.

First, you can use useState like this and give your intended image.

const [imgSrc, setImgSrc] = useState("Invalid Image Source");

then, in your image component, you can simply do this. (make sure to spell onError correctly)

<img src={imgSrc} onError = {() => setImgSrc("https://picsum.photos/200")} />

in the setImgSrc() give the image you want as the default.

Hope this was helpful!

Arush Nath
  • 11
  • 1