Skip to content

Instantly share code, notes, and snippets.

@WomB0ComB0
Created November 13, 2024 04:42
Show Gist options
  • Save WomB0ComB0/eb65ae2c54309e238cbd294350d41d9b to your computer and use it in GitHub Desktop.
Save WomB0ComB0/eb65ae2c54309e238cbd294350d41d9b to your computer and use it in GitHub Desktop.
Lazy image wrapper, React
import React, {
type PropsWithChildren,
cloneElement,
isValidElement,
type DetailedReactHTMLElement,
type ImgHTMLAttributes,
type FC,
Children,
} from "react";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const LazyImageWrapper: FC<PropsWithChildren<any>> = (props) => {
const { children } = props;
const cloneChildren = Children.map(children, (child) => {
if (isValidElement(child) && child.type === "img") {
return cloneElement(
child as DetailedReactHTMLElement<
ImgHTMLAttributes<HTMLImageElement>,
HTMLImageElement
>,
{ loading: "lazy" },
);
}
return child;
});
return <>{cloneChildren}</>;
};
export default LazyImageWrapper;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment