React Tutorial- Image Lazy Load And Handle Broken Image Example

In this post, we will learn how to easily lazy load images in React Js apps. We will also learn how to handle image-loading errors in React.

 

In order to create a lazy load images component React, we will see how to use useEffect, useCallback and useState hooks in the functional component.

In addition, we will see how to handle broken images or image load errors in react function component using React hooks.

 

We will make an imgProfile component. It will take certain props that will lazy load images and at the same time, displays a unique image when the wrong path or the broken image url is passed to the imgProfile component.

 

We will see the steps to be followed for doing so:

Step 1- Build React App

Firstly, we will open the console screen of the terminal, type and run the following command using NPM:

npx create-react-app my-react-app

Since the pp installation is done, we will navigate to the app folder through the command:

cd my-react-app

 

Step 2- Make New Function Component

A component function helps handle any functionality we need.

For that, we make the components/ folder, navigate into the directory and then create the imgProfile.js file. We need to use the given code:

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

 

Step 3- Configure Bootstrap In React

Now, we have to install the Bootstrap library using the below command:

npm i bootstrap

 

Now, we will move to the App.js file where we have to import the Bootstrap CSS path:

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
function App() {
  return <div></div>;
}
export default App;

 

Step 4- Handle Image Lazy Load And Image Load Error

We need to place useState, useCallback and useEffect hooks in the function component.

Now, we will add the given code within the components/ImgProfile.js file:

import React from "react";
const ImgProfile = ({ path, placeholder, loadError, ...props }) => {
  const [img, initImg] = React.useState(placeholder || path);
  const onLoad = React.useCallback(() => {
    initImg(path);
  }, [path]);
  const onError = React.useCallback(() => {
    initImg(loadError || placeholder);
  }, [loadError, placeholder]);
  React.useEffect(() => {
    const imageObjt = new Image();
    imageObjt.src = path;
    imageObjt.addEventListener("load", onLoad);
    imageObjt.addEventListener("error", onError);
    return () => {
      imageObjt.removeEventListener("load", onLoad);
      imageObjt.removeEventListener("error", onError);
    };
  }, [path, onLoad, onError]);
  return <img {...props} alt={img} src={img} />;
};
export default ImgProfile;

 

Step 5- Set Props In ImgProfile Component

Here, we need to add or import the Bootstrap module and profile component into the global component.

Further, we will also import the ImgProfile component. Then, we create the two components for dealing with the image lazy loading and broken image.

We will add the given code to the src/App.js file:

import ImgProfile from "./components/ImgProfile";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
function App() {
  return (
    <div className="container">
      <h2 className="mb-3">
        React Image Lazy Load and Image Load Error Example
      </h2>
      <div className="row">
        <div className="col-6">
          <ImgProfile
            style={{ width: 340 }}
            path="https://i.postimg.cc/8CVt73NY/wonderlane-N-As0-VQu7s-unsplash.jpg"
            placeholder="https://i.postimg.cc/8CVt73NY/wonderlane-N-As0-VQu7s-unsplash.jpg"
          />
        </div>
        <div className="col-6">
          <ImgProfile
            style={{ width: 340 }}
            path="https://brokenpath.com/broken.jpg"
            placeholder="https://i.postimg.cc/RZvT9tdr/guerrillabuzz-crypto-pr-Wtol-M5hsj14-unsplash.jpg"
            loadError="https://i.postimg.cc/RZvT9tdr/guerrillabuzz-crypto-pr-Wtol-M5hsj14-unsplash.jpg"
          />
        </div>
      </div>
    </div>
  );
}
export default App;

 

Step 6- Test React App

Now, we will start the React development server using the npm command:

npm start

 

Conclusion

In this Rect example, we have learned how to buildĀ  React image lazy loading component using function component and React hooks.

We have also seen how to handle broken images or image-loading errors in React Js.

 

Thanks

Leave a Reply

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