2

Image not in correct format error

Hi, on my webpage there are few images which are giving this response when going directly to the image link. I am using react in the frontend. Is it possible to check before loading these type of images that if there is no proper image at the location, load a not found image or 404 image. There are many ways which enable us to show 404 image if there is nothing at the link. But here I am getting something at the link but the webpage is not able to render this because its not in the correct format or whatever is the reason. Is there any way to handle this in react?

Thanks

2

1 Answer 1

2

You can use onError event handler on <img> tags like this :

import React from "react";

class ImageComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { imageStatus: "loading", error: false };
  }

  handleImageLoaded() {
    this.setState({ imageStatus: "loaded", error: false });
  }

  handleImageError() {
    this.setState({ imageStatus: "failed to load", error: true });
  }

  render() {
    return (
      <div>
        <img
          src={this.state.error ? 'static/404.png' : this.props.imageUrl}
          onLoad={this.handleImageLoaded.bind(this)}
          onError={this.handleImageError.bind(this)}
        />
        {this.state.imageStatus}
      </div>
    );
  }
}
export default ImageComponent;
Sign up to request clarification or add additional context in comments.

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.