9

I've created an image element using Semantic UI React.

<Image floated="right" size="mini" src="/someImageUrl.png" />

If the image's src property doesn't load, a broken image placeholder is displayed instead.

enter image description here

How can I hide this broken image placeholder and show no image instead when my image doesn't load?

I've tried following the answer from this StackOverflow answer which suggests using

<Image src="Error.src" onerror="this.style.display='none'"/> 

But I receive the error Expected 'onError' listener to be a function.

3 Answers 3

13

You can pass the img element to an onError handler through the handler event's target property, and change the image's src to '' or style.display to none.

<Image src={imageObject.Url} onError={i => i.target.src=''} />
<Image src={imageObject.Url} onError={i => i.target.style.display='none'} />
Sign up to request clarification or add additional context in comments.

Comments

5

You can use:

<Image src={imageObject.Url} onError={e => e.target.style.display = 'none'} />

Comments

0

I faced a problem where the img icon is rendered with src = "". Because of an initial state source which I set to empty strings

In the useEffect / (Component Did Mount). I update that state to the desired url.

The problem is the broken img icon stays while the url is being downloaded.

Also the onError={} doesn't trigger.

The solution was a conditional render.

{ 
source === "" ? null : <Img src={source} onError={someMethod} /> 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.