LazyLoad
Overview
The LazyLoad component defers the loading of off-screen content (like images, videos, or heavy components) until it is about to enter the viewport.
This improves initial page load times and enhances performance.
Preview
- Preview
- Code
Loading...
<LazyLoad
threshold="100px"
animation="fade"
once={true}
placeholder={<div style={{ height: "200px", background: "#eee" }}>Loading...</div>}
>
<div style={{
height: "200px",
background: "#ccc",
display: "flex",
justifyContent: "center",
alignItems: "center"
}}>
Loaded Content
</div>
</LazyLoad>
Installation
- npm
- Yarn
- pnpm
- manual
npx @mindfiredigital/ignix-ui add lazyload
yarn @mindfiredigital/ignix-ui add lazyload
pnpm @mindfiredigital/ignix-ui add lazyload
import React, { useEffect, useState, useRef } from "react";
export interface LazyLoadProps {
children: React.ReactNode;
className?: string;
threshold?: string; // Distance from viewport to trigger loading
placeholder?: React.ReactNode; // Placeholder content
once?: boolean; // Load only once
animation?: "fade" | "slide" | "none"; // Animation type
}
export const LazyLoad: React.FC<LazyLoadProps> = ({
children,
className,
threshold = "100px",
placeholder = null,
once = true,
animation = "fade",
}) => {
const [isVisible, setIsVisible] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
setIsVisible(true);
if (once) observer.disconnect(); // Stop observing if `once` is true
}
},
{ rootMargin: threshold }
);
if (containerRef.current) {
observer.observe(containerRef.current);
}
return () => {
if (containerRef.current) observer.unobserve(containerRef.current);
};
}, [threshold, once]);
const getAnimationStyle = () => {
switch (animation) {
case "fade":
return { opacity: isVisible ? 1 : 0, transition: "opacity 0.5s ease" };
case "slide":
return {
transform: isVisible ? "translateY(0)" : "translateY(20px)",
opacity: isVisible ? 1 : 0,
transition: "transform 0.5s ease, opacity 0.5s ease",
};
default:
return {};
}
};
return (
<div ref={containerRef} className={className} style={getAnimationStyle()}>
{isVisible ? children : placeholder}
</div>
);
};
Usage
Import the component:
import { LazyLoad } from './components/ui';
<LazyLoad
threshold="100px"
animation="fade"
once={true}
placeholder={<Skeleton />}
>
<HeavyContent />
</LazyLoad>