3

I created a component named Avatar and it wraps Image of Next.JS. The parent component of Avatar uses src prop (which is a string) to change the image source (this will be a remote source). If it does not specify the src prop, then a default local image will be used as shown in the following code snippet.

import Image from "next/image";
import styles from "./Avatar.module.css";
import AvatarPhoto from "../images/avatar-default.png";

export const Avatar = ({ src, alt, size = 47 }) => {
  return (
    <div className={styles.imgContainer}>
      <Image
        className={styles.img}
        src={src ?? AvatarPhoto}
        alt={alt}
        width={size}
        height={size}
      />
    </div>
  );
};

What I could not achieved is if the specified source is invalid, how can I show the local image. For example; if there is not a image in the specified source (If the Get request for the source results with 404 Error), I want to use the default avatar image.

Is there a fallback property of Next's Image ? If not, how can I do that ?

eneski
  • 1,575
  • 17
  • 40

1 Answers1

3
export const Avatar = ({ src, alt, size = 47 }) => {
  const [error, setError] = useState(false);

  return (
    <div className={styles.imgContainer}>
      <Image
        className={styles.img}
        src={!error ? src : AvatarPhoto}
        alt={alt}
        width={size}
        height={size}
        onError={() => setError(true)}
      />
    </div>
  );
};


Inder
  • 1,711
  • 1
  • 3
  • 9
  • thanks it works. But, where did you find onError property? It is not mentioned in the docs https://nextjs.org/docs/api-reference/next/image – eneski May 03 '22 at 11:12
  • 2
    Image component underneath is a html `` tag. Every html element has a onload and onerror event listener. Because its javascript, it becomes onError and onLoad @eneski – Inder May 03 '22 at 11:13