Search code examples
javascriptnext.jsmern

How to replace actual Image with dummy image when image is not present


<div className="bg-[#F8F8F8] flex items-center justify-center px-2 py-10">
  <Image src={image} alt="course image" width={100} height={100} />
</div>

When the image is unavailable due to an error, I want to replace it with a dummy image. How can I do that?


Solution

  • import fallbackImage from ./assets/dummy-image.jpg;

    import the fallback image and Conditional src:

    The src attribute uses the original image. If the original image is unavailable or fails to load, the src event handler sets the src to the fallback image.

    src={image || fallbackImage}