8

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.

Dave Clark
  • 2,243
  • 15
  • 32

3 Answers3

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'} />
Dave Clark
  • 2,243
  • 15
  • 32
4

You can use:

<Image src={imageObject.Url} onError={e => e.target.style.display = 'none'} />
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
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} /> 
}
arthas
  • 680
  • 1
  • 8
  • 16