Created
November 13, 2024 04:42
-
-
Save WomB0ComB0/eb65ae2c54309e238cbd294350d41d9b to your computer and use it in GitHub Desktop.
Lazy image wrapper, React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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