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

I want when image is not available due to error so replace it with dummy image how can i do that?

2

Answers


  1. 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}
    
    Login or Signup to reply.
  2. To replace a failing image with a dummy image in a React component, you can use the onError event on the Image tag to handle image loading errors. Here’s a simplified version:

    import Image from 'next/image';
    import React, { useState } from 'react';
    
    function CourseImage({ src }) {
      const [imageUrl, setImageUrl] = useState(src);
    
      const handleError = () => {
        setImageUrl('/path-to-your-dummy-image.png'); // Replace with your dummy image path
      };
    
      return (
        <div className="bg-[#F8F8F8] flex items-center justify-center px-2 py-10">
          <Image
            src={imageUrl}
            alt="course image"
            width={100}
            height={100}
            onError={handleError}
          />
        </div>
      );
    }
    
    export default CourseImage;
    

    Key Points:

    • Use useState to manage the image URL.
    • Use the onError callback to switch to a dummy image if the original fails to load.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search