This image should load correctly
This should not
Broken images can break our users experience, managing error states gracefully lets us have more control over how our UI should look like if an unexpected action occur. Right now the next/image
component does not implement a fallback
property (but it might do it in the future), but we can implement it ourselves.
const ImageWithFallback = ({ fallback = fallbackImage, alt, src, ...props }) => { const [error, setError] = useState(null) useEffect(() => { setError(null) }, [src]) return ( <Image alt={alt} onError={setError} src={error ? fallbackImage : src} {...props} /> ) }
Now we have a way of determine a fallback
url for our images that will be used in case our original src
fails to load.
This image should load correctly
This should not
We also ensure to reset the error everytime our src
changes as changing it might solve the issue. You can also change the layout
or width
and height
props when being in an error state if needed.