0

I use react for an SPA

I have this <img /> component

I pull the src from a URL that is created via props of the functional component that renders the <img />

Sometimes the URL works sometimes it returns a 404 but the img tag I still rendered and with the default .. missing image icon ...

HOW can I make it not render or render some random transparent img IF the first URL is not valid (404)

2 Answers2

3

As @Sterling Archer mentioned, your problem is relevant with Checking if image does exists using javascript .

To sum it up, that is listening on img's onerror event, and once your url returns 404, onerror will be triggered.

const onError = () => {
    this.setState({ urlError: true })
}

render() {
    return (this.state.urlError ? <img onerror={this.onError} /> : null)
}
Kinka
  • 425
  • 6
  • 15
-1

You could do a cors xhttp request to determine If the status is 404 and then set a state boolean. Use this bool to choose wether to render the image or return null

L4B0MB4
  • 151
  • 1
  • 11