FallbackLazyImage
An extension of the LazyImage component that renders a Fallback component based on the image load state.
In addition to src, the width, height, and fallback props are required. It is recommended to match the fallback size to the specified width and height.
The duration prop is the transition-duration value used when transitioning from the fallback component to the actual image after it has loaded.
Code
Interface
typescript
interface IntersectionObserverInit {
root?: Element | Document | null;
rootMargin?: string;
threshold?: number | number[];
}
interface LazyImageProps
extends React.ComponentProps<'img'>,
IntersectionObserverInit {
src: string;
}
typescript
interface FallbackLazyImageProps extends LazyImageProps {
fallback: JSX.Element;
width: string | number;
height: string | number;
duration?: CSSProperties['transitionDuration']; // default: 0.2s
}
const FallbackLazyImage: React.ForwardRefExoticComponent<
Omit<FallbackLazyImageProps, 'ref'> & React.RefAttributes<HTMLImageElement>
>;
Props
| Name | Type | Default | Description |
|---|---|---|---|
src | string | - | Image URL |
fallback | JSX.Element | - | Fallback component displayed while the image is loading |
width | string | number | - | Image width |
height | string | number | - | Image height |
duration | CSSProperties['transitionDuration'] | '0.2s' | transition-duration when switching from fallback to the actual image |
Usage
Basic Usage
typescript
import { FallbackLazyImage } from '@modern-kit/react';
import img1 from '../assets/img1.png';
const Example = () => {
const skeletonStyle = useMemo(
() => ({
width: '400px', // Match the actual image size.
height: '400px', // Match the actual image size.
backgroundColor: 'green',
}),
[]
);
return (
<div>
<FallbackLazyImage
fallback={<div style={skeletonStyle} />}
width={400}
height={400}
src={img1}
alt="img1"
/>
</div>
);
};
Wrapper Styling: css Styling
- The
Image Wrapperinside theFallbackLazyImagecomponent has a default classlazy-image-wrapper. You can use this class to control its styling.
/* css stylesheet */
.lazy-image-wrapper {
border-radius: 12px;
overflow: hidden;
}
.lazy-image-wrapper > img {
/* image styling */
}
<FallbackLazyImage {/* ...props */} />
Wrapper Styling: css-in-js Styling
- You can create a new styled component using the inheritance feature of
css-in-js.
const Image = styled(FallbackLazyImage)`
border-radius: 12px;
overflow: hidden;
& > img {
/* image styling */
}
`;
<Image {/* ...props */} />
Example
Scroll down.