I have a react component that is the detail view from a list.
I am trying to replace the image with a default image if the image does not exist and there is a 404 er
Previous versions have the bug; they don't count that src
could be changed. So I made my ultimate solution and it:
src
is changedonError
(means you can pass onError
to ImageWithFallback
like you usually do with ![]()
) Here it is:
import React, { useState, useCallback, useEffect } from 'react';
import noImage from 'src/svg/no-image.svg';
export const ImageWithFallback = React.forwardRef(
(
{
onError,
...props
}: React.DetailedHTMLProps<
React.ImgHTMLAttributes,
HTMLImageElement
>,
ref: React.Ref,
) => {
const [imageLoadFailed, setImageLoadFailed] = useState(false);
const handleError = useCallback(
(e: React.SyntheticEvent) => {
if (imageLoadFailed) return;
setImageLoadFailed(true); // to avoid infinite loop
if (onError) {
onError(e);
}
},
[imageLoadFailed, setImageLoadFailed, onError],
);
useEffect(() => {
setImageLoadFailed(false); // in case `src` is changed
}, [props.src]);
return (
);
},
);