Spaces:
Sleeping
Sleeping
File size: 914 Bytes
6df1c09 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import { useEffect, useRef, useState } from "react";
interface ImageWithFallbackProps {
src: string;
alt: string;
className?: string;
}
export function ImageWithFallback({ src, alt, className }: ImageWithFallbackProps) {
const imgRef = useRef<HTMLImageElement>(null);
const [imgSrc, setImgSrc] = useState(src);
const [error, setError] = useState(false);
useEffect(() => {
setImgSrc(src);
setError(false);
}, [src]);
const handleError = () => {
if (!error && imgSrc.startsWith('/')) {
setError(true);
// Try with explicit origin if relative URL
const baseURL = import.meta.env.MODE === "development"
? "http://127.0.0.1:8000"
: window.location.origin;
setImgSrc(`${baseURL}${imgSrc}`);
}
};
return (
<img
ref={imgRef}
src={imgSrc}
alt={alt}
className={className}
onError={handleError}
/>
);
} |