DEV Community

taiseen
taiseen

Posted on

Default image load, while error happen at image loading time

It's common to load static/dynamic images at our wed application. But if some time images are fail to load for several reason as like:-

a) Broken image link,
b) Missing from our assets folder,
c) Wrong naming of image file - etc...

So, by default catch these kind of image loading fail case, we can add some little set of logic that prevent our UI to display annoying placeholder that come with default browser behavior.

Note: this implementation is base on ReactJS, you can extract this logic as per your development environment.

Its become good, if you keep you default image file under "/public" folder if you are working on React project. Then you can directedly access this image from your source code.

const YourComponent = () => {


  const handleImgLoadingError = (e) => {

    // default image add, if associated image is not available...
    e.target.src = '/images/YOUR-DEFAULT-IMAGE-FILE-NAME.jpg';

  };


  return (

    <div>
      <img
        src={`YOUR-IMAGE-SOURCE`}
        alt={`YOUR-IMAGE-FILE-NAME`}
        onError={(e) => handleImgLoadingError(e)}
      />
    </div>

  );
};

export default YourComponent;
Enter fullscreen mode Exit fullscreen mode

Hope its will be little helpful for your project beatification.

Thank You :)

Top comments (0)