0

i'm trying to set a default value for image src in the Image component in next.js. i can't find any option to do that, for case the server response with status code 400. corrently i'm getting in the console text like:

The requested resource isn't a valid image for <url for invalid image here> received inode/x-empty

i want to return a default image in case the requested image doesn't found. thanks in advece!

i tried to build a component like:

const CustomImage = ({
                         src = placeholder,
                         alt = "alt",
                         size = "125px",
                         cycle = false
                     }) => {
    return <Image
        src={src}
        width={size}
        height={size}
        alt={alt}
        quality={"100"}
        layout={"fixed"}
        style={{
            borderRadius:
                cycle ? "50%" : ".15em"
        }}
    />
}

and it doesn't help.

EDIT: after a lot of searching, i have a component that should take care of all the cases, but when i'm getting 404 error it stil showing broken image.

const CustomImage = ({
                         src = placeholder,
                         alt = "alt",
                     }) => {

    const [imageError, setImageError] = useState(false);

    return <Image
        src={imageError ? placeolder : src}
        width={size}
        height={size}
        alt={alt}
        onLoadingComplete={(result) => {
            if (result.naturalWidth === 0) setImageError(true)
        }}
        onError={(event) => setImageError(true)}
        onEmptied={() => setImageError(true)}
    />
}
YeudaBy
  • 11
  • 5

1 Answers1

1

In my case, the right way to do that is by onErrorCapture.

YeudaBy
  • 11
  • 5