ImageWithPreview component renders a low-quality image placeholder (LQIP) while the full-resolution image loads, providing a better user experience with progressive image loading.
Import
How It Works
The component renders two<img> elements:
- A preview image (LQIP) that displays immediately
- The full-resolution image that loads in the background
Props
The URL or data URI of the low-quality image placeholder to display while the full image loads.
Allows rendering as a different element type. Defaults to
img.CSS styles to apply to both the preview and full images.
Alternative text for the image. Applied to whichever image is currently visible.
HTML id attribute. Applied only to the preview image.
CSS class name. Applied only to the preview image.
Image width in pixels. Applied to both images and used to calculate aspect ratio.
Image height in pixels. Applied to both images and used to calculate aspect ratio.
<img> attributes (or attributes for the element specified in as).
Loading Behavior
Preview Image
The preview image is rendered with:- The
previewURL as thesrc - All specified dimensions, classes, and styles
- A
data-lqipattribute for styling/selection - Only visible until the full image loads
Full Image (While Loading)
While loading, the full image is rendered with:- Minimum 10px × 10px dimensions (to avoid lazy-loading)
- Absolute positioning with
z-index: -10 opacity: 0to hide itpointerEvents: 'none'anduserSelect: 'none'- A
data-loading="true"attribute
Full Image (After Loading)
After loading completes:- All special loading styles are removed
- The specified
styleprop is applied - The preview image is unmounted
- The
data-loadingattribute is removed
Usage Examples
Basic Usage
With Custom Styling
With Different Element Type
Type Definition
Implementation Notes
- The component uses
useEffectto check if the image is already cached (ref.current?.complete) and immediately callsonLoadif so - The aspect ratio is automatically calculated from
widthandheightprops and applied to the preview image - The loading state is managed internally with
useState - The component prevents layout shift by maintaining consistent dimensions throughout the loading process