"use client";
import { useEffect, useState } from "react";
type Props = React.ImgHTMLAttributes<HTMLImageElement> & {
src: string;
fallbackSrc?: string;
};
export default function ImageWithFallback({
fallbackSrc,
src,
...props
}: Props) {
const [hasErrored, setHasErrored] = useState<boolean>(false);
const [activeSrc, setActiveSrc] = useState<string>(src);
useEffect(() => {
console.log(hasErrored);
if (hasErrored && fallbackSrc !== undefined) setActiveSrc(fallbackSrc);
}, [hasErrored]);
return (
<img
{...props}
src={activeSrc}
onError={(e) => {
setHasErrored(true);
}}
/>
);
}
"use client";
import { useEffect, useState } from "react";
type Props = React.ImgHTMLAttributes<HTMLImageElement> & {
src: string;
fallbackSrc?: string;
};
export default function ImageWithFallback({
fallbackSrc,
src,
...props
}: Props) {
const [hasErrored, setHasErrored] = useState<boolean>(false);
const [activeSrc, setActiveSrc] = useState<string>(src);
useEffect(() => {
console.log(hasErrored);
if (hasErrored && fallbackSrc !== undefined) setActiveSrc(fallbackSrc);
}, [hasErrored]);
return (
<img
{...props}
src={activeSrc}
onError={(e) => {
setHasErrored(true);
}}
/>
);
}