1

I'm making a request to an api and within all the objects are an array of images, but only some of them are returning

I get the error GET http://******/image/******/403 for each image that has failed to load, this is due to my access being denied which I'm not concerned about because I'm aware that some images are going to fail to load because of this (hope that makes sense).

How can I mitigate/bypass this situation and pass a fallback image in case the default http images return with a 403, or not pass a fallback image at all?

I hope that all makes sense, and thanks for your help :)

  • 1
    How can we do that without any code? – mindmaster Sep 12 '19 at 08:24
  • Please have a look at [this checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) and try to edit your question to provide a [mcve]. Up to now your question is kind of vague, making it hard to see what you are doing and where the problem is. – xiawi Sep 12 '19 at 08:26
  • The React way is to use a custom Image component that will try and load the Image first, assign an `onerror` to it and set the `src` based on that. Live example: https://codesandbox.io/s/sad-sound-efjus –  Sep 12 '19 at 08:36

2 Answers2

3

You can use the onError property on your image

<img src="mySuperImage.jpg" onError={handleImgError} />

const handleImgError = e => {
  e.target.src = "defaultImage.jpg"
}
Maxime Girou
  • 1,511
  • 2
  • 16
  • 32
2

img tag can take onError handler. You can make your code in a function and place it in onError handler in your image.

imageFail = (event) => {
   // your code
}

<img src="..." onError={this.imageFail} />
Akram Badah
  • 417
  • 3
  • 12