DEV Community

taiseen
taiseen

Posted on

2

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 :)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️