1

I am trying to create sort of media gallery for React app, but the problem is that sometimes user may upload some demmaged pictures and i need to somehow check if image is possible to read and not demmaged before displaying it. I know on <image/> tag there are property onerror where you display other image if first one didn't work.

 <img src={url} style={style} onError={this.hideImg}/> 

But the problem is that i use a div with image-background so it won't be working for me, and bessides that i also need to display some notification message that file is demmaged. Does anyone knows is there are some ways to check if file is valid before displaying it in react ?

2 Answers 2

4

You can create an image in memory (ie, not on the page), and wait for that to load or error out. For example:

const Example = ({ url }) => {
  const [status, setStatus] = useState('loading');
  useEffect(() => {
    const img = new Image();
    img.onload = () => {
      setStatus('success');
    }
    img.onerror = () => {
      setStatus('error');
    }
    img.src = url
    return () => {
      img.onload = null;
      img.onerror = null;
    }
  }, [])

  if (status === 'loading') {
    return null;
  } else if (status === 'error') {
    return <div>Error loading image</div>
  } else {
    return <div style={{ backgroundImage: `url(${url})`}} />
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much , for answer
0

Use the onError handler. It solves the issue of image is shown or not it can handle the error on the image for example

<img
 src={url}
 alt="favicon"
 style={{ width: "20px", margin: "10px" }}
 onError={(e: any) => {
 e.target.onerror = null;
 e.target.src =
 "https://via.placeholder.com/20?text=Error";
  e.target.alt = "Error loading favicon";
  }}
          />

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.