Home > Software design >  React img onError not firing
React img onError not firing

Time:05-31

I am trying to use a third-party API for getting YouTube thumbnails with higher resolution, which sometimes fails with code 404. If I fail to fetch the image, I would like to replace the src with the default YouTube thumbnail retrieved using its own API (I have the url stored in a json). When I tried to implement this using the img one rror event, it appears that nothing is fired when the fetch fails. Does anybody know what's going on? Thanks!

const TestView = () => {

    const videoId = "1KUZHKI-BDk"

    return (
        <div>
            <img src={`https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`} one rror={() => {console.log("errored")}}></img>
        </div>
    )
}

CodePudding user response:

It's nothing to do with React. Try visiting that url in your browser with a random string for the videoId. It will still display an image - in this case the default youtube thumbnail. So even though it's technically a 404, and your browser will report it as such, the image still has something to display so it won't fire the onError function.

If you replace the url in your code with something that is definitely a 404, your code works fine. Run the snippet below where i've swapped out youtube for google and you'll see your error message.

function one rror() {
  console.log('errored')
}
<img src="https://img.google.com/vi/some-random-id/maxresdefault.jpg" one rror="onError()" />

  • Related