title: Is there a way to check if an image exists before setting the image source in React when the image source has concatenated variables?
body: <p>I'm creating a component that contains an image with a dynamic source. It's dynamic in that it takes 3 props that get concatenated into the URL of the image. No matter what I try, I can't seem to get it to stop giving me the error, 'Cannot find module' for images that don't exist.</p>
  
  <p>I have tried checking to see if the image exists with the image-exists package and using ajax to check if the image exists. I have also tried adding onError to change the state from the URL.</p>
  
  <pre><code>import React from "react";
  
  export class Drawing extends React.Component {
      constructor(props) {
          super(props);
          this.state = { src: "" };
          this.setSource = this.setSource.bind(this);
      }
  
      setSource() {
          this.setState({
              src: require(`../../../../img/products/${this.props.type}/models/${this.props.product}-${this.props.model.replace(/\s+/g, "-").toLowerCase()}-specs-drawing.png`)
          });
      }
  
      componentWillMount() {
          this.setSource();
      }
  
      render() {
          return &lt;img src={this.state.src} alt="Specification Drawing" /&gt;;
      }
  }
  </code></pre>
  
  <p>It almost seems as the the componentWillMount is getting called every time I change the dropdown selection. The dropdown changes the model which will change the image source based on the dropdown. It is showing the image correctly only if the image for that path exists. Otherwise it gives me the error, 'Cannot find module ...image-path'.</p>