HOW TO LAZY LOAD IMAGE IN REACTJS
Candie
Posted on March 26, 2024
Lazy loading images in your react project optimizes your website and also makes it visually appealing to visitors.
We can achieve this in various ways, but I will only highlight two ways
APPROACH 1
The HTML image tag now accepts a loading
attribute that takes in either the lazy
attribute or the trigger
attribute
The lazy
attribute tells the browser to only load and download images currently on the browser's viewport and defer other images load and download to when the user scrolls to them.
The eager
attribute tells the browser to load all images immediately.
For optimization purposes, adding the lazy
attribute reduces build and browser load time.
<img loading='lazy' />
APPROACH 2
We will be using a third party react library to optimize image load and download.
The library is react-lazy-load-image-component
Run the command below to install this package to your react project.
npm install react-lazy-load-image-component
If you're building a large project where you will be using the img
tag a lot, I will advise you create a reusable component.
I will name mine Image.jsx
Step 1: Import the react-lazy-load-image-component
package to the file
Step 2: Import the lazy load effect you would like to use, iIwill be using blur
here.
Step 3: Render the LazyLoadImage
component in the file and pass in the needed props as illustrated below
Step 4: Save the file and preview the image
You have successfully optimized your project by implementing lazy image loading.
import { LazyLoadImage } from "react-lazy-load-image-component";
import "react-lazy-load-image-component/src/effects/blur.css";
export default function Image({src, styles}) {
return (
<>
<LazyLoadImage
alt={alt}
className="gallery-img"
effect="blur"
src={src}
width="100%"
style={styles}
/>
</>
);
}
You can customize the effect to your taste, read more about the package here;
Let me know if this was helpful to you in the comment section
Posted on March 26, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.