React Check If Image Loaded or Error Occurred Tutorial

React Image OnLoad and OnError event handler example. In this tutorial, we are going to teach you how to manage image handler events in React js application. We will introduce you step-by-step to with image onLoad and onError event handlers.

You will be taught how to check if the image is entirely loaded in React js. Not just that, we will also teach you how to display errors when the image is not loaded due to some error occurring or the original image path is not valid.

We will bind onLoad and onError event handlers to the image component. Create an essential functional component in our react app; this will seamlessly detect if all the images are correctly loaded.

To handle image errors in React, we will hide the broken image icon by replacing a “no image available” placeholder in this react onError example.

Create React Project

To begin with this tutorial, ensure that you have Node and Npm configured in your system.

You have to install a new React app, use the command to create the application.

npx create-react-app my-react-app

However, If app is already created, then jump onto the next step.

Else, move into the application folder.

cd my-react-app

Add Bootstrap Package

Run the following command, and install the Bootstrap library into the React project.

If you are comfortable with writing custom CSS, then don’t install this package.

npm install bootstrap

Create New Component

Create the features/ folder, after that create the ImageUpload.js file. Add the following code into the file and create your functional component.

import React from 'react'

function ImageUpload() {
  return (
    <div></div>
  )
}

export default ImageUpload

Create Image OnLoad and OnError Component

We created two image components: Both the image components will show messages when the image is uploaded, and an error occurs while uploading an image.

The image error handling component will display an error only when the main image is not loaded.

Add the code into the features/ImageUpload.js file.

import React from "react";

const DemoImg_One = "https://no-image.jpeg";
const DemoImg_Two =
  "https://i.postimg.cc/RCG2J693/kenny-eliason-z-FSo6bn-ZJTw-unsplash.jpg";

const No_Img =
  "https://placehold.jp/e00b72/ffffff/350x350.png?text=No%20Image%20Available";

const ImageUpload = () => {
  const handlerImgLoad = (e) => {
    console.log(`Image has ${e.currentTarget.src} uploaded.`);
    if (e.currentTarget.className !== "error") {
      e.currentTarget.className = "success";
    }
  };

  const handlerImgError = (e) => {
    e.currentTarget.src = No_Img;
    e.currentTarget.className = "error";
  };

  return (
    <div>
      <img
        src={DemoImg_One}
        onLoad={handlerImgLoad}
        onError={handlerImgError}
        alt="Demo 1"
      />

      <img
        src={DemoImg_Two}
        onLoad={handlerImgLoad}
        onError={handlerImgError}
        alt="Demo 2"
      />
    </div>
  );
};

export default ImageUpload;

Update Global Component

Here we have reached the final step of this tutorial, and we need to add the image component into the src/App.js file.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import ImageUpload from "./features/ImageUpload";

function App() {
  return (
    <div className="container mt-5">
      <h2 className="mb-3">
        React Detect If Image Loaded with Image Error Handler Example.
      </h2>
      <ImageUpload />
    </div>
  );
}

export default App;

Run React Server

Head over to the console, type the provided command, then hit enter and start the app.

npm start

This will run the react server and display the url that you can use to view and test the app.

http://localhost:3000

React Check If Image Loaded or Error Occurred Tutorial

Conclusion

The smallest of things makes the user experience better. Improvement in user experience leads to more excellent user retention. This is directly related to superb usability.

Through this guide, we have tried to cover how to find out if the image loading is completed in React Js. And if the image path is incorrect, we learned how to display the fallback placeholder image—and how to successfully handle image loading and image loading error through onLoad and onError event handlers.