So, I'm mapping some images from the API response, and they come with an array of five img
sources(urls). By default, src
of the image should be first url
from the given array, but in some cases that url
is broken, and should be replaced with the next working url
from the array. I've tried doing something like this:
<img src={snapshots[0]} alt="" onError={(e) => this.onError(e, snapshots)} />
imageExists = url => {
let img = new Image();
img.src = url;
if (img.width !== 0) {
return true
} else {
return false
}
}
onError = (e, snapshots) => {
if (this.imageExists(snapshots[1])) {
e.target.src = snapshots[1]
} else if (this.imageExists(snapshots[2])) {
e.target.src = snapshots[2]
} else if (this.imageExists(snapshots[3])) {
e.target.src = snapshots[3]
} else if (this.imageExists(snapshots[4])) {
e.target.src = snapshots[4]
} else {
e.target.src = 'https://via.placeholder.com/400x300'
}
}
But sometimes this checking method works, sometimes it doesn't, it just skips to the placeholder image, even if there are working urls. Any advice?