️
A simple React image component that suspends while loading.
Install the package.
yarn add react-suspense-img
Import the Img
component and image resource
cache.
import { Img, resource } from 'react-suspense-img';
Use the Img
component as you would a standard img
element. However, ensure to wrap it (at the desired place in the tree) with a ErrorBoundary
and React.Suspense
. The Img
component will suspend (while loading) or throw an error (if an error occurred loading the image).
// Start fetching early, following the render-as-you-fetch pattern.
resource.preloadImage('https://placekitten.com/12/34');
const Component = () => (
<ErrorBoundary>
<React.Suspense fallback="Loading...">
<Img src="https://placekitten.com/12/34" width={64} alt="Kitten" />
</React.Suspense>
</ErrorBoundary>
);
Want to see examples of what this could look like? See some of the examples here.
A small component that wraps img
but suspends while the image is loading.
src
: the only required prop, the image source to display....
: all of the standard image props, for examplealt
,className
, etc.
The image resource to cache images and determine if a given image has loaded or if it needs to suspend.
preloadImage(src: string)
: preload the given source image. This is the only method that is necessary to use. This should be called before using the givensrc
with theImg
component to follow the render-as-you-fetch pattern.read(src: string)
: read a given source from the cache. If it has not loaded it will throw a promise. If it has errored it will throw an error. If it has loaded it will return the source. This method is used within theImg
component and should never need to be called directly.clear()
: clear the entire image resource cache. This may be useful for running between tests to always start with an empty cache.
- Built with TSDX.
- Inspired by
relay-experimental
. - Inspired by
suspense-experimental-github-demo
.