React Js Tutorial- How To Handle Images onLoad And onError Events In React Js

React Images Loaded And Broken Images Example; JavaScript offers Image onLoad and onError event handlers that make managing the behavior of the image extremely facile.

In this React tutorial, we will learn how to detect images loaded in React and how to check if the image is broken using the image event handlers in React Js.

 

We will create a User function component where we will go through the basic process of working with the image onLoad event handler, not just that but also image onError event handlers.

 

The onError event in React helps check whether the error occurred during image loading. In this post, we will use the onError() event handler to detect the broken image.

The onError event handler triggers when an error manifests while the image is loading. It happens mainly when the specified URL refers to corrupt image data.

The onLoad image handler is added to an image tag. It detects when the images are loading in React or in any JavaScript-based apps.

 

Let’s see the steps to be followed:

Step 1- Download React App

The primary step is just to create the environment by having Node and NPM set in our system. We have to execute the given command:

npx create-react-app react-blog
cd react-blog

 

Step 2- Build The Functional Component

The second step is to make the components/ directory in the src/ folder. Subsequently, we make the new file and name it User.js:

To create the function code, we would need such type of JavaScript function code:

import React from 'react'
function User() {
  return (
    <div>User page</div>
  )
}
export default User

 

Step 3- Setting Up Bootstrap In React

We can make the I designing processes faster by adding Bootstrap CSS framework in React Project.

Below is the command given for that:

npm install bootstrap

Now, we will open the App.js file that we can find in the src/ folder. Then, we import the Bootstrap CSS path derived from the node_modules folder:

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

 

Step 4- Find Image Loaded Or Broken Image

We have managed to make two methods imageOnLoad and imageOnError. Both the custom functions will display information about image onLoad and onError events.

Now, we will put the given code within the components/User.js file:

import React from "react";
const Image_1 = "https://image-not-found.png";
const Image_2 =
  "https://i.postimg.cc/8CVt73NY/wonderlane-N-As0-VQu7s-unsplash.jpg";
const BrokenImage =
  "https://i.postimg.cc/RZvT9tdr/guerrillabuzz-crypto-pr-Wtol-M5hsj14-unsplash.jpg";
const User = () => {
  const imageOnLoad = (event) => {
    console.log(`Picture successfully ${event.currentTarget.src} loaded.`);
    if (event.currentTarget.className !== "error") {
      event.currentTarget.className = "success";
    }
  };
  const imageOnError = (event) => {
    event.currentTarget.src = BrokenImage;
    event.currentTarget.className = "error";
  };
  return (
    <div className="container mt-3">
      <div className="row">
        <div className="col-6">
          <img
            src={Image_2}
            onLoad={imageOnLoad}
            onError={imageOnError}
            width="255"
            alt="Picture Two"
          />
        </div>
        <div className="col-6">
          <img
            src={Image_1}
            onLoad={imageOnLoad}
            onError={imageOnError}
            width="255"
            alt="Picture One"
          />
        </div>
      </div>
    </div>
  );
};
export default User;

 

Step 5- Register New Component IN App Js

It’s time to add one component to another component. So, we open the global component file i.e. App.js and add the below code to it:

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import User from "./components/User";
function App() {
  return (
    <div>
      <h2>React JS On Load and On Error Image Event Handler Example</h2>
      <User />
    </div>
  );
}
export default App;

 

Step 6- Test React Application

Now, we will test the app. We can do this by using the below command:

npm start

 

Conclusion

In this React tutorial, we have seen how to find if the image is finished loading or throws an error during the loading in React JS.

We have done this just to show how to fire the image onError event handler and how to show the image is broken or the image path is wrong.

 

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *