Lazy Images with Fallback / ReactJS

Pablo Garcia
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={...} />
)
}

--

--

Pablo Garcia
Pablo Garcia

Written by Pablo Garcia

Senior Engineer at Netflix, ex-Staff Architect 2 at PayPal. M.S. in Computer Science w/specialization in Computing Systems. B.Eng. in Computer Software.

No responses yet