0

I have a folder with images of wines all named with their code (ie: FMP-HTR17) and want to display the associated image if it exists, but if the image isn't in the folder I want to render a stock photo instead.

Right now I have a ternary operation which I thought would return false if the image wasn't in the folder, but since I have a code for the wine it returns true (obviously). But I can't figure out how to check to see if the image exists!

//   Finds image with Code if available:   
{ `/images/bottle/${this.props.Code}.png` ? <Image className="cardImage" src={`/images/bottle/${this.props.Code}.png`}/>
        :
        // Else renders Stock Image:
        <Image className="cardImage"src='/images/StockRED.png' />
      }

How do I see if a file exists with the name I'm looking for?

elainecadman
  • 69
  • 2
  • 8
  • Can you share your code pls? Also when you say folder do you just have the images in a folder or it is an data structure which contains a list of images? – Neil Jun 04 '19 at 23:52

2 Answers2

0

For stock image, I think you could use the onerror event.

<img src="invalid_link" onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';">

Note that it's important to void the onerror event when it happens, to avoid infinite loop in the case the stock image loading fails.

You can take a look in this answer, from where I got the example above: How does one use the onerror attribute of an img element

  • Thank you! Yes, this is what I was looking for. I just didn't know about onerror. This is another explanation: https://stackoverflow.com/questions/38527759/how-to-check-for-broken-images-in-react-js – elainecadman Jun 05 '19 at 22:24
0

How to check for broken images in React JS

I was previously unaware of onError, very helpful! The example above worked for me.

elainecadman
  • 69
  • 2
  • 8