Search code examples
javascriptreactjsimagelazy-loading

How to render default image before rendering the actual image in react js?


I render image by props like this :

function AdImg(props) {
    const propImg = `http://localhost:5000/${props.img}`;
    return (
                <img
                    placeholder={require('../../../app-data/img/default.png')}
                    alt="ad-img"
                    className="img-fluid rounded"
                    src={propImg}
                />
    );
}

export default AdImg;

The propblem is when this component renders it doesn't show the placeholder till it render the actual image .

How can I set a default placeholder image so it shows the placeholder till it renders the actual image ?


Solution

  • Something like this should work

    export default function App() {
      const [isLoading, setIsLoading] = useState(true);
    
      function onLoad() {
        // delay for demo only
        setTimeout(() => setIsLoading(false), 1000);
    
       // setIsLoading(false)
      }
    
      return (
        <>
          <img
            alt="ad-img"
            width={300}
            src="https://via.placeholder.com/300x200/FF0000"
            style={{ display: isLoading ? "block" : "none" }}
          />
          <img
            alt="ad-img"
            width={300}
            src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcS1hIjBaj0A0XNB_xAozRAcFs6Gr0DQhWTGiQ&usqp=CAU"
            style={{ display: isLoading ? "none" : "block" }}
            onLoad={onLoad}
          />
        </>
      );
    }
    

    ...we're displaying 2 images, the placeholder and the actual image. While the actual image is loading, we're going to display the placeholder, when its loaded we're going to hide the placeholder and show the actual image.

    Edit cranky-breeze-kp7yg