0

Could you please tell me how to replace src of image, while making list in react? I have one list in which there is an image and it's caption. I want to exchange src url in my img tag when image not present. If image is present on server then it's fine, if not - I want to replace src url to this one http://punemirror.indiatimes.com/photo/55813567.cms.

Here is my code https://codesandbox.io/s/KOrGKp3B8

I have tried like this: there is function which detect whether image present or not. But how I will use this function in react?

  imageExists(url, callback) {
            var img = new Image();
            img.onload = function () {
                callback(true);
            };
            img.onerror = function () {
                callback(false);
            };
            img.src = url;
        }
user5711656
  • 3,310
  • 4
  • 33
  • 70

1 Answers1

0

You can create a component which will handle this logic for you:

class SmartImage extends React.Component {
  constructor() {
    super();
    this.state = { fallback: true };
  }

  componentDidMount() {
    this.checkImage();
  }

  componentDidUpdate(prevProps) {
    if (prevProps.image !== this.props.image) {
       this.checkImage();
    }
  }

  checkImage() {
     let img = new Image(this.props.img);
     img.onload =  () => {
       this.setState({ fallback: false });
     };
     img.onerror = () => {
       this.setState({ fallback: true });
     };
  }

  render() {
    return (
      <img src={this.state.fallback ? this.props.imgFallback : this.props.img} />
    );
  }
}

And instead of rendering img tags directly, you'd render SmartImage components like this: <SmartImage img={url1} imgFallback={url2} />

It basically checks if the image is loaded successfully each time its changed, and on mount, and changes the state accordingly, which then renders accordingly.

Gershon Papi
  • 5,008
  • 3
  • 24
  • 50