Next.js Discord

Discord Forum

Image fallback

Answered
Erenay posted this in #help-forum
Open in Discord
the code works properly but these errors appear in the console. does it cause a problem?

ImageFallback.tsx
"use client";

import Image, { ImageProps } from "next/image";
import { useEffect, useState } from "react";

interface ImageFallbackProps extends Omit<ImageProps, 'src'> {
  src: string;
  fallbackSrc: string;
}

export default function ImageFallback({ 
  src, 
  fallbackSrc, 
  ...rest 
}: ImageFallbackProps) {
  const [imgSrc, setImgSrc] = useState(src);

  useEffect(() => {
    setImgSrc(src);
  }, [src]);

  return (
    <Image
      {...rest}
      src={imgSrc}
      onLoadingComplete={(result) => {
        if (result.naturalWidth === 0) {
          setImgSrc(fallbackSrc);
        }
      }}
      onError={() => {
        setImgSrc(fallbackSrc);
      }}
    />
  );
}


 ⨯ upstream image response failed for A_404_IMAGE_URL 404
Image with src "A_404_IMAGE_URL" is using deprecated "onLoadingComplete" 
property. Please use the "onLoad" property instead.

 ⨯ ./app/components/ImageFallback.tsx
Module parse failed: Unexpected token (18:16)
|         src: imgSrc,
|         onLoad: (result)=>{
>             if (<invalid> === 0) {
|                 setImgSrc(fallbackSrc);
|             }
Answered by chisto
onLoad={(e) => console.log(e.target.naturalWidth)}
View full answer

3 Replies

try changing onLoadingComplete to onLoad to see if it goes away and it still work?
it giving typescript error. because result.naturalWidth doesnt exist. 'SyntheticEvent<HTMLImageElement, Event>'
onLoad={(e) => console.log(e.target.naturalWidth)}
Answer