'Display fallback image for a broken image

Instead of a picture, the server sometimes returns https://i.imgur.com/aPbF7Gc.png (backend being repaired) this is why it doesn't work

<img
  src={imageSrc}
  onError={() => setImageSrc(fallbackImage)}
/>

option to set fallbackImage instead of broken image link. onError event doesn't happen, I checked. Are there options to fix it?



Solution 1:[1]

onError event doesn't happen, I checked.

I'm not sure what trouble you experienced, but providing a callback to handle the error event works fine for images:

<div id="root"></div><script src="https://unpkg.com/[email protected]/umd/react.development.js"></script><script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="env,react">

const {useState} = React;

const defaultSrc = 'https://images.dog.ceo/nope.jpg';
const fallbackSrc = 'https://images.dog.ceo/breeds/cockapoo/bubbles1.jpg';

function Example () {
  const [imageSrc, setImageSrc] = useState(defaultSrc);

  return (
    <>
      <div>
        Fallback image used: {imageSrc === fallbackSrc ? '?' : '?'}
      </div>
      <img
        alt="dog"
        onError={() => {
          if (imageSrc !== fallbackSrc) setImageSrc(fallbackSrc);
        }}
        src={imageSrc}
        style={{maxWidth: '100%'}}
      />
    </>
  );
}

ReactDOM.render(<Example />, document.getElementById('root'));

</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jsejcksn