Lazy Images with Fallback / ReactJS
Sep 27, 2021
To load an image lazily with HTML, we can use the loading attribute on an <img />
tag (see compatibility & polyfill).
When an image doesn’t load, we can fallback by using the onerror
attribute of the <img />
elements.
function LazyImage({ src, fallback, ...otherAttributes }) {
return (
<img
src={src}
loading="lazy"
onError={e => {
e.target.onerror = null // prevent an infinite error loop
e.target.src = fallback
}}
{...otherAttributes}
/>
)
}
Usage
function App() {
return (
<LazyImage src="..." fallback="..." style={...} />
)
}