React Image Component and Hook

4.1.0 · maintenance · verified Sun Apr 19

React Image is a library providing a robust `<img>` tag replacement and a `useImage` hook for React applications. It focuses on enhancing image loading by supporting multiple image sources for fallback, displaying custom preloader components while images are loading, and gracefully handling image loading errors. The current stable version is 4.1.0, but the package was last published over three years ago, suggesting a maintenance rather than active development cadence. A key differentiator is its internal `useImage` hook, which leverages React Suspense by default for declarative image loading states. It explicitly advises against using it for lazy loading, recommending native browser `loading="lazy"` for that purpose. It allows developers to specify any React element as a loading indicator or an error fallback, providing a more polished user experience than default browser behaviors.

Common errors

Warnings

Install

Imports

Quickstart

This example showcases the `Image` component with a `Suspense` boundary, providing a custom loader and a fallback component if all specified images fail to load. It uses `srcList` for multiple fallback image sources.

import React, { Suspense } from 'react';
import { Image } from 'react-image';

const PlaceholderComponent: React.FC = () => (
  <div style={{ background: '#f0f0f0', height: '200px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
    Loading Image...
  </div>
);

const ErrorFallbackComponent: React.FC = () => (
  <div style={{ background: '#ffcccc', color: '#cc0000', height: '200px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
    Failed to load image.
  </div>
);

const App: React.FC = () => {
  const imageUrls = [
    'https://picsum.photos/800/600?random=1', // Primary image
    'https://picsum.photos/600/400?random=2', // Fallback image 1
    'https://upload.wikimedia.org/wikipedia/commons/thumb/1/11/Test-Logo.svg/783px-Test-Logo.svg.png' // Fallback image 2
  ];

  return (
    <div style={{ fontFamily: 'sans-serif', padding: '20px' }}>
      <h1>React Image Example</h1>
      <p>This demonstrates loading an image with a custom placeholder and multiple fallbacks.</p>
      <div style={{ maxWidth: '800px', margin: '20px auto', border: '1px solid #ddd' }}>
        <Suspense fallback={<PlaceholderComponent />}>
          <Image
            srcList={imageUrls}
            loader={<PlaceholderComponent />}
            alt="Random unsplash image"
            style={{ width: '100%', height: 'auto', display: 'block' }}
            errorFallback={<ErrorFallbackComponent />}
          />
        </Suspense>
      </div>
      <p>Note: The first valid URL from `srcList` will be used. If all fail, `errorFallback` is shown.</p>
    </div>
  );
};

export default App;

view raw JSON →