Skip to content

Commit

Permalink
fix: fallback not working in ssr
Browse files Browse the repository at this point in the history
  • Loading branch information
afc163 committed Feb 9, 2023
1 parent b30dad9 commit 6195aa8
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/Image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ interface CompoundedComponent<P> extends React.FC<P> {

type ImageStatus = 'normal' | 'error' | 'loading';

function isImageValid(src) {
return new Promise(resolve => {
let img = document.createElement('img');
img.onerror = () => resolve(false);
img.onload = () => resolve(true);
img.src = src;
});
}

const ImageInternal: CompoundedComponent<ImageProps> = ({
src: imgSrc,
alt,
Expand Down Expand Up @@ -123,9 +132,7 @@ const ImageInternal: CompoundedComponent<ImageProps> = ({
};

const onError = (e: React.SyntheticEvent<HTMLImageElement, Event>) => {
if (onImageError) {
onImageError(e);
}
onImageError?.(e);
setStatus('error');
};

Expand Down Expand Up @@ -173,6 +180,14 @@ const ImageInternal: CompoundedComponent<ImageProps> = ({
}
};

React.useEffect(() => {
isImageValid(src).then(isValid => {
if (!isValid) {
setStatus('error');
}
});
}, [src]);

// Keep order start
// Resolve https://github.com/ant-design/ant-design/issues/28881
// Only need unRegister when component unMount
Expand Down Expand Up @@ -239,7 +254,7 @@ const ImageInternal: CompoundedComponent<ImageProps> = ({
<img
{...imgCommonProps}
ref={getImgRef}
{...(isError && fallback ? { src: fallback } : { onLoad, onError, src: imgSrc })}
{...(isError && fallback ? { src: fallback } : { onLoad, src: imgSrc })}
width={width}
height={height}
/>
Expand Down

0 comments on commit 6195aa8

Please sign in to comment.