4

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"
       />

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Filip
  • 855
  • 2
  • 18
  • 38
  • Does this answer your question? [How to check if a pariticular fileExists in reactjs](https://stackoverflow.com/questions/48259512/how-to-check-if-a-pariticular-fileexists-in-reactjs) – Sinan Yaman Oct 12 '21 at 10:30
  • 1
    You need to look inside the component to see if it's looking for `onerror` - if it is you can use something like `onerror="this.style.display='none'"` – StudioTime Oct 12 '21 at 11:08

1 Answers1

5

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"
/>
juliomalves
  • 42,130
  • 20
  • 150
  • 146