Getting started
Show a lazy image with a placeholder and a blur effect.
Show a lazy image
Import LazyLoadImage and use it like an <img>.
import { LazyLoadImage } from "lazymage";
export const Photo = () => (
<LazyLoadImage
alt="A lake at sunset"
height={480}
src="/lake.jpg"
width={640}
/>
);
The image renders when it is 100 px from the viewport. To change this distance, set threshold.
Add an effect
An effect shows while the image loads. lazymage has three effects: blur, opacity, and black-and-white.
- Import the CSS file of the effect one time in your app.
- Set the
effectprop to the name of the effect.
import { LazyLoadImage } from "lazymage";
import "lazymage/effects/blur.css";
export const Photo = () => (
<LazyLoadImage
alt="A lake at sunset"
effect="blur"
height={480}
placeholderSrc="/lake-small.jpg"
src="/lake.jpg"
width={640}
/>
);
placeholderSrc is a small version of the image. lazymage shows it as the background until the full image loads. With the blur effect, the user sees a blurred preview.
Show a fallback image
Set fallbackSrc to show a different image when src fails to load. lazymage tries the fallback one time.
<LazyLoadImage
alt="User avatar"
fallbackSrc="/avatar-default.png"
src={user.avatarUrl}
/>
Lazy load a component
Use LazyLoadComponent to render any content only when it comes near the viewport.
import { LazyLoadComponent } from "lazymage";
export const Comments = () => (
<LazyLoadComponent placeholder={<p>Loading comments…</p>}>
<CommentList />
</LazyLoadComponent>
);
Next steps
- LazyLoadImage: see all the props.
- Styling: change the effects and use the
data-stateattribute. - SSR and React Server Components: show images above the fold at once.