Home > other >  How to replace broken image url into different component?
How to replace broken image url into different component?

Time:05-28

I want to render another component if the Image URL is broken as shown in the image.enter image description here. I tried one rror that doesn't help me..

if the image is broken I want To Render the short Name of the user

SS

CodePudding user response:

Try a utility for the existance of the file

function checkImage(url) {
  var request = new XMLHttpRequest();
  request.open("GET", url, true);
  request.send();
  request.onload = function() {
    status = request.status;
    if (request.status == 200) //if(statusText == OK)
    {
      console.log("image exists");
    } else {
      console.log("image doesn't exist");
    }
  }
}
checkImage("path-to-image-url");

CodePudding user response:

Not sure how you tried to use onerror and didn't work.

But here is an example that make use of the onerror attribute on the HTML img element:

function ImageWithFallback({ src, children, ...props }) {
  const [hasError, setHasError] = useState(false);
  return hasError ? (
    children
  ) : (
    <img {...props} src={src} one rror={() => setHasError(true)} />
  );
}

function App() {
  return (
    <div>
      <ImageWithFallback src="https://placekitten.com/100/100">
        <p>Fallback</p>
      </ImageWithFallback>
      <ImageWithFallback src="bad_url">
        <p>Fallback</p>
      </ImageWithFallback>
    </div>
  );
}

You may extend <ImageWithFallback /> to have it reset the state when the props src changes.

  • Related