Smaller (< 2KB) alternative of react-simple-img that doesn't include IntersectionObserver polyfill.
npm install --save react-even-simpler-img
import { ImageLoader, SimpleImg } from 'react-even-simpler-img';
First, wrap your app with :
ReactDOM.render(
<ImageLoader>
<App />
</ImageLoader>,
rootNode
);
Use as if it's a normal HTML Image element
<SimpleImg src="https://picsum.photos/40" />
To lazy load images, set importance
prop to low
:
<SimpleImg src="https://picsum.photos/40" importance="low" />
This library uses IntersectionObserver to lazy load images. If the browser doesn't support it, this library will gracefully degrade to eager loading approach.
To display a fallback when the image fails to load, you need to wrap it with an Error Boundary.
// you need to have your own implementation
// of React error boundary
import ErrorBoundary from './MyErrorBoundary';
<ErrorBoundary fallback={<MyImgFallback />}>
<SimpleImg src="https://rubbish.xyz/foo/bar.jpg" />
</ErrorBoundary>;
Also check out react-error-boundary for ready-made ErrorBoundary component!