Filip
Filip

Reputation: 945

Don't display next/image component when the image doesn't exist

I'm using next/image and I want the image to not render at all when the path to the image is invalid, eg. the image doesn't exist. Now it displays the little icon and alt name. I don't want to display anything in that case. Is that possible? Since it's frontend I can't use fs to check, so I'm not sure what to do

      <Image
         src={`/scroll-${router.locale}.svg`}
         alt="scroll"
         width="240px"
         height="240px"
         className="opacity-50"
       />

Upvotes: 5

Views: 5478

Answers (2)

Jiř&#237; Zeman
Jiř&#237; Zeman

Reputation: 21

Placeholder solution. I know... This is not correct answer for you, but for someone else helps with placeholder solution.

'use client';

import type { FC } from 'react';
import { useState } from 'react';

import Image from 'next/image';
import type { ImageProps } from 'next/image';
import fallbackImgSrc from '/public/img/placeholders/star-wars.webp';

type ImageWithFallbackProps = ImageProps & {
  fallbackSrc?: string;
};

export const ImageWithFallback: FC<ImageWithFallbackProps> = ({
  fallbackSrc = fallbackImgSrc,
  ...props
}) => {
  const [error, setError] = useState(false);
  return (
    <Image
      {...props}
      src={error ? fallbackSrc : props.src}
      onError={() => {
        return setError(true);
      }}
    />
  );
};

Upvotes: 1

juliomalves
juliomalves

Reputation: 50228

You can extend the built-in next/image and add an onError handler to not render the component if the image fails to load.

import React, { useState } from 'react';
import Image from 'next/image';

const ImageWithHideOnError = (props) => {
    const [hideImage, setHideImage] = useState(false);

    return (
        !hideImage && (
            <Image
               {...props}
               onError={() => {
                   setHideImage(true);
               }}
            />
        )
    );
};

export default ImageWithHideOnError;

You can then use the component instead of the next/image.

<ImageWithHideOnError
    src={`/scroll-${router.locale}.svg`}
    alt="scroll"
    width="240px"
    height="240px"
    className="opacity-50"
/>

Upvotes: 8

Related Questions