28 lines
		
	
	
		
			611 B
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
			
		
		
	
	
			28 lines
		
	
	
		
			611 B
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
| // src/components/ImageWithFallback.tsx
 | |
| import { useState, useEffect } from 'react';
 | |
| 
 | |
| interface Props extends React.ImgHTMLAttributes<HTMLImageElement> {
 | |
|   fallbackSrc: string;
 | |
| }
 | |
| 
 | |
| export const ImageWithFallback = ({ src, fallbackSrc, ...props }: Props) => {
 | |
|   const [imgSrc, setImgSrc] = useState(src);
 | |
|   const [error, setError] = useState(false);
 | |
| 
 | |
|   useEffect(() => {
 | |
|     setError(false);
 | |
|     setImgSrc(src);
 | |
|   }, [src]);
 | |
| 
 | |
|   const handleError = () => {
 | |
|     setError(true);
 | |
|   };
 | |
| 
 | |
|   return (
 | |
|     <img
 | |
|       src={error || !imgSrc ? fallbackSrc : imgSrc}
 | |
|       onError={handleError}
 | |
|       {...props}
 | |
|     />
 | |
|   );
 | |
| }; |