Reputation: 1299
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)
Upvotes: 1
Views: 2098
Reputation: 425
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)
}
Upvotes: 3
Reputation: 171
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
Upvotes: -1