diff --git a/components/parts/ProductImage.tsx b/components/parts/ProductImage.tsx new file mode 100644 index 0000000..5e522f2 --- /dev/null +++ b/components/parts/ProductImage.tsx @@ -0,0 +1,42 @@ +'use client'; + +import { useEffect, useRef } from 'react'; + +const PLACEHOLDER = '/images/product-placeholder.svg'; + +interface ProductImageProps { + src?: string | null; + alt: string; + className?: string; + width?: number; + height?: number; + loading?: 'lazy' | 'eager'; +} + +export function ProductImage({ src, alt, className, width, height, loading }: ProductImageProps) { + const hasErrored = useRef(false); + + // Reset the loop guard whenever src changes (e.g. navigating between products) + useEffect(() => { + hasErrored.current = false; + }, [src]); + + function handleError(e: React.SyntheticEvent) { + if (hasErrored.current) return; + hasErrored.current = true; + e.currentTarget.src = PLACEHOLDER; + } + + return ( + // eslint-disable-next-line @next/next/no-img-element + {alt} + ); +}