Skip to content

Commit

Permalink
Merge pull request #4262 from tloncorp/po/tlon-3323-handle-errored-im…
Browse files Browse the repository at this point in the history
…ages-gracefully

images: provide default fallback for errored images
  • Loading branch information
patosullivan authored Dec 6, 2024
2 parents c0c1091 + b3bb24c commit 93e9a77
Showing 1 changed file with 50 additions and 8 deletions.
58 changes: 50 additions & 8 deletions packages/ui/src/components/Image.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,38 @@
import { Image as BaseImage, ImageErrorEventData } from 'expo-image';
import { ReactElement, useCallback, useState } from 'react';
import { Platform, StyleSheet } from 'react-native';
import { styled } from 'tamagui';
import { SizableText, View, styled } from 'tamagui';

import { Icon } from './Icon';

const DefaultImageFallback = () => (
<View flex={1} alignItems="center" justifyContent="center">
<Icon type="Placeholder" color="$tertiaryText" />
<SizableText color="$tertiaryText">Unable to load image</SizableText>
</View>
);

const WebImage = ({
source,
style,
alt,
onLoad,
onError,
fallback,
...props
}: any) => {
const [hasError, setHasError] = useState(false);

const handleError = (e: React.SyntheticEvent<HTMLImageElement>) => {
setHasError(true);
if (onError) {
onError({
error: new Error('Image loading failed'),
target: e.currentTarget,
});
}
};

const WebImage = ({ source, style, alt, onLoad, ...props }: any) => {
const handleLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
if (onLoad) {
// Mimic expo-image's onLoad event structure
Expand All @@ -16,7 +45,15 @@ const WebImage = ({ source, style, alt, onLoad, ...props }: any) => {
}
};

const { contentFit } = props;
const { contentFit } = props;

if (hasError && fallback) {
return fallback;
}

if (hasError) {
return <DefaultImageFallback />;
}

return (
<img
Expand All @@ -29,6 +66,7 @@ const WebImage = ({ source, style, alt, onLoad, ...props }: any) => {
objectFit: contentFit ? contentFit : undefined,
}}
onLoad={handleLoad}
onError={handleError}
{...props}
/>
);
Expand All @@ -51,11 +89,15 @@ export const ImageWithFallback = StyledBaseImage.styleable<{
[onError]
);

return hasErrored ? (
fallback
) : (
<StyledBaseImage ref={ref} {...props} onError={handleError} />
);
if (hasErrored && fallback) {
return fallback;
}

if (hasErrored) {
return <DefaultImageFallback />;
}

return <StyledBaseImage ref={ref} {...props} onError={handleError} />;
},
{
staticConfig: {
Expand Down

0 comments on commit 93e9a77

Please sign in to comment.