Skip to content

Commit

Permalink
add: fallback feature to image
Browse files Browse the repository at this point in the history
  • Loading branch information
nhussein11 committed Jul 31, 2023
1 parent 5a1bd44 commit 0d01700
Showing 1 changed file with 26 additions and 11 deletions.
37 changes: 26 additions & 11 deletions src/lib/components/image/index.tsx
Original file line number Diff line number Diff line change
@@ -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<HTMLImageElement> {
hash: string
Expand All @@ -10,34 +12,47 @@ export interface IpfsImageProps extends HTMLAttributes<HTMLImageElement> {
lazy?: boolean
style?: CSSProperties
className?: HTMLProps<HTMLElement>['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<string>('')

useEffect(() => {
const imgSrcCleaned = getIpfsURL(gateway, hash)
setImgSrc(imgSrcCleaned)
}, [hash, gateway])

const handleOnError = (e: SyntheticEvent<HTMLImageElement, Event>): void => {
if (e.type === 'error') {
setImgSrc(fallbackImage)
}
}

return (
<img
src={imgSrc}
alt={imgAlt}
width={imgWidth}
height={imgHeight}
alt={alt}
width={width}
height={height}
style={style}
className={className}
loading={imgLoading}
onError={(e) => {
handleOnError(e)
}}
{...props}
/>
)
Expand Down

0 comments on commit 0d01700

Please sign in to comment.