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...
Loading...
Loading...
Loading...
Loading...
<LazyLoad
threshold="0px"
animation="fade"
once={false}
placeholder={<div className="p-6 text-center">Loading...</div>}
>
<div className="bg-gray-200 rounded-lg shadow text-center p-10">
Your Content
</div>
</LazyLoad>
Installation
- CLI
- manual
ignix add component lazyload
import React, { useEffect, useRef, useState } from "react";
export interface LazyLoadProps {
children: React.ReactNode;
className?: string;
threshold?: string; // e.g. "100px"
placeholder?: React.ReactNode;
once?: boolean;
animation?: "fade" | "slide" | "none";
}
export const LazyLoad: React.FC<LazyLoadProps> = ({
children,
className,
threshold = "0px",
placeholder = null,
once = true,
animation = "none",
}) => {
const ref = useRef<HTMLDivElement | null>(null);
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
if (!ref.current) return;
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setIsVisible(true);
if (once) {
observer.disconnect(); // unobserve after first load
}
} else if (!once) {
setIsVisible(false); // re-hide if once=false
}
});
},
{ rootMargin: threshold }
);
observer.observe(ref.current);
return () => observer.disconnect();
}, [threshold, once]);
// Animation classes
const animationClass =
animation === "fade"
? "transition-opacity duration-700 ease-in-out opacity-0 data-[visible=true]:opacity-100"
: animation === "slide"
? "transition-transform duration-700 ease-in-out translate-y-4 opacity-0 data-[visible=true]:translate-y-0 data-[visible=true]:opacity-100"
: "";
return (
<div
ref={ref}
className={`${className ?? ""} ${animationClass}`}
data-visible={isVisible}
>
{isVisible ? children : placeholder}
</div>
);
};
Usage
Import the component:
import { LazyLoad } from './components/ui';
Example usage:
<LazyLoad
threshold="100px"
animation="fade"
once={true}
placeholder={<Skeleton />}
>
<HeavyContent />
</LazyLoad>
Props
| Prop | Type | Default | Description |
|---|---|---|---|
children | React.ReactNode | required | The content to lazy load. |
className | string | "" | Custom CSS class names. |
threshold | string | "100px" | Distance from the viewport to start loading (e.g., "0px", "200px"). |
placeholder | React.ReactNode | null | Placeholder shown until the content is loaded. |
once | boolean | true | If true, content loads only once. If false, it toggles visibility when entering/exiting viewport. |
animation | "fade" | "slide" | "none" | "fade" | Animation effect applied when content appears. |