RItesh Gupta
RItesh Gupta

Reputation: 83

How to detect whether all images in a react component is loaded using react hooks

I am working on a next js application. I know ES6 but new to react. I have a component which is called from a useEffect fetch data function from another component. Below is my component code:

export default function HeaderResults(cars) {    
    return(
      <div className="results">          
          {cars.results &&
            cars.results.map((result) => {
              return (
                <Link
                  href={`/cars/${createLink(result.title)}/${result.id}`}
                  onClick={() => clearSearch()}
                >
                  <div className="result-item">
                    <img
                      src={`https://api.cars.com/images/${result.poster_car}`} alt="..."
                    />
                    <div className="title" key={result.name}>
                      {result.name}
                    </div>
                  </div>
                </Link>
              );
            })}
        </div>
    );
}

Here cars is the response object i get from the fetch data function. I am using it by having {HeaderResults(cars)} in my render function.

This gives me around 20 or more results. The problem is each image is loaded separately and my result window is getting re arranged every time an image is loaded which looks bad.

What i want is to show the results only if all the images are loaded or else a loader is displayed. I tried creating a image component for this and using ref. But no luck.

I am using next js and want to do it using react hooks. Is there a way to achieve this without using any third party library? Solutions are welcome. Thanks

Upvotes: 1

Views: 3875

Answers (1)

nghiaht
nghiaht

Reputation: 795

Here is my idea

  • Render all images but set the CSS style to visibility: hidden

    By making them hidden like that way, browser still load images!

  • Add an onLoad for each image and update the loaded images list

  • Loop checking if all images are loaded, if they are, set visibility: visible

Check out my sample https://codesandbox.io/s/count-of-loaded-images-pd3qn?file=/pages/index.js

Upvotes: 4

Related Questions