diff --git a/src/lib/components/image/index.tsx b/src/lib/components/image/index.tsx index 10441ed..d125aa8 100644 --- a/src/lib/components/image/index.tsx +++ b/src/lib/components/image/index.tsx @@ -1,5 +1,7 @@ -import type { CSSProperties, HTMLAttributes, HTMLProps } from 'react' +import type { CSSProperties, HTMLAttributes, HTMLProps, SyntheticEvent } from 'react' +import { useEffect, useState } from 'react' import { getIpfsURL } from '../../utils/ipfs' +import { DEFAULT_FALLBACK_IMAGE } from '../../const/images' export interface IpfsImageProps extends HTMLAttributes { hash: string @@ -10,34 +12,47 @@ export interface IpfsImageProps extends HTMLAttributes { lazy?: boolean style?: CSSProperties className?: HTMLProps['className'] + fallbackImage?: string } export const ImageIPFS = ({ hash, gateway, - width, - height, - alt, + width = 100, + height = 100, + alt = 'IPFS Image', lazy, style, className, + fallbackImage = DEFAULT_FALLBACK_IMAGE, ...props }: IpfsImageProps): JSX.Element => { - const imgSrc = getIpfsURL(gateway, hash) - const imgWidth = width ?? 100 - const imgHeight = height ?? 100 - const imgAlt = alt ?? 'IPFS Image' const imgLoading = lazy === true ? 'lazy' : 'eager' + const [imgSrc, setImgSrc] = useState('') + + useEffect(() => { + const imgSrcCleaned = getIpfsURL(gateway, hash) + setImgSrc(imgSrcCleaned) + }, [hash, gateway]) + + const handleOnError = (e: SyntheticEvent): void => { + if (e.type === 'error') { + setImgSrc(fallbackImage) + } + } return ( {imgAlt} { + handleOnError(e) + }} {...props} /> )