Skip to content

Commit

Permalink
[@mantine/core] Image: fix possible permanent placeholder after hydra…
Browse files Browse the repository at this point in the history
…tion (#630)
  • Loading branch information
Stouffi committed Jan 8, 2022
1 parent e00f6c2 commit f7b9c5b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
2 changes: 1 addition & 1 deletion .nvmrc
@@ -1 +1 @@
v14.9.0
v14.17.0
18 changes: 14 additions & 4 deletions src/mantine-core/src/components/Image/Image.tsx
@@ -1,6 +1,6 @@
import React, { useState, forwardRef } from 'react';
import React, { useState, forwardRef, useEffect, useRef } from 'react';
import { DefaultProps, MantineNumberSize, ClassNames } from '@mantine/styles';
import { useDidUpdate } from '@mantine/hooks';
import { useDidUpdate, useMergedRef } from '@mantine/hooks';
import { Text } from '../Text';
import { Box } from '../Box';
import { ImageIcon } from './ImageIcon';
Expand Down Expand Up @@ -70,6 +70,16 @@ export const Image = forwardRef<HTMLDivElement, ImageProps>(
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState(!src);
const isPlaceholder = withPlaceholder && (!loaded || error);
const internalImgRef = useRef<HTMLImageElement>(null);
const mergedImgRef = useMergedRef(...[...(imageRef ? [imageRef] : []), internalImgRef]);

useEffect(() => {
const { current } = internalImgRef;
if (current?.complete) {
setError(current.naturalHeight === 0);
setLoaded(current.naturalHeight !== 0);
}
}, [src]);

useDidUpdate(() => {
setLoaded(false);
Expand All @@ -85,7 +95,8 @@ export const Image = forwardRef<HTMLDivElement, ImageProps>(
src={src}
alt={alt}
style={{ objectFit: fit, width, height }}
ref={imageRef}
ref={mergedImgRef}
{...imageProps}
onLoad={(event) => {
setLoaded(true);
typeof imageProps?.onLoad === 'function' && imageProps.onLoad(event);
Expand All @@ -94,7 +105,6 @@ export const Image = forwardRef<HTMLDivElement, ImageProps>(
setError(true);
typeof imageProps?.onError === 'function' && imageProps.onError(event);
}}
{...imageProps}
/>

{isPlaceholder && (
Expand Down

0 comments on commit f7b9c5b

Please sign in to comment.