How to detect images loaded in React

I had to do a manual deep linking hook, scrolling automatically down in a web application to a specific section, but the delay on images loaded were doing this scroll wrong.

Then, how to detect the loading of the images before executing any action in …


This content originally appeared on DEV Community and was authored by Alejandro Martinez

I had to do a manual deep linking hook, scrolling automatically down in a web application to a specific section, but the delay on images loaded were doing this scroll wrong.

Then, how to detect the loading of the images before executing any action in react? The next hook uses eventListener with load and errorevents, and detect the

import { useState, useEffect, RefObject } from "react";

export const useOnLoadImages = (ref: RefObject<HTMLElement>) => {
  const [status, setStatus] = useState(false);

  useEffect(() => {
    const updateStatus = (images: HTMLImageElement[]) => {
      console.log(images.map((image) => image.complete));
      setStatus(
        images.map((image) => image.complete).every((item) => item === true)
      );
    };

    if (ref.current) {
      const imagesLoaded = Array.from(ref.current.querySelectorAll("img"));
      if (imagesLoaded.length === 0) {
        setStatus(true);
      } else {
        imagesLoaded.forEach((image) => {
          image.addEventListener("load", () => updateStatus(imagesLoaded), {
            once: true
          });
          image.addEventListener("error", () => updateStatus(imagesLoaded), {
            once: true
          });
        });
      }
    }

    return undefined;
  }, [ref]);

  return status;
};

Note: is important to add both event load and error to avoid any blocking after load pages, in case any image don't load correctly.

To use it you have to pass a ref wrapper to limit the search images.

import { useRef } from "react";
import { useOnLoadImages } from "./hooks/useOnLoadImages";
import "./styles.css";

export default function App() {
  const wrapperRef = useRef<HTMLDivElement>(null);
  const imagesLoaded = useOnLoadImages(wrapperRef);

  return (
    <div className="App" ref={wrapperRef}>
      <h1>Use on Load Images hook</h1>
      <h2>How to detect images loaded in React</h2>
      <div>
        <p>{imagesLoaded && "Images loaded"}</p>
        <img
          src="https://i.pinimg.com/564x/8b/09/87/8b09873753b3fede7abc1ffd8a147c2e.jpg"
          alt="image1"
        />
        <img
          src="https://i.pinimg.com/564x/39/ed/15/39ed1564db8313300d9759dbbf1e6e2a.jpg"
          alt="image2"
        />
        <img
          src="https://i.pinimg.com/564x/bc/ec/24/bcec24fd07fca68fd172d3df5d8b2bb9.jpg"
          alt="image3"
        />
      </div>
    </div>
  );
}

Here there a demo Link


This content originally appeared on DEV Community and was authored by Alejandro Martinez


Print Share Comment Cite Upload Translate Updates
APA

Alejandro Martinez | Sciencx (2021-10-05T03:15:20+00:00) How to detect images loaded in React. Retrieved from https://www.scien.cx/2021/10/05/how-to-detect-images-loaded-in-react/

MLA
" » How to detect images loaded in React." Alejandro Martinez | Sciencx - Tuesday October 5, 2021, https://www.scien.cx/2021/10/05/how-to-detect-images-loaded-in-react/
HARVARD
Alejandro Martinez | Sciencx Tuesday October 5, 2021 » How to detect images loaded in React., viewed ,<https://www.scien.cx/2021/10/05/how-to-detect-images-loaded-in-react/>
VANCOUVER
Alejandro Martinez | Sciencx - » How to detect images loaded in React. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/10/05/how-to-detect-images-loaded-in-react/
CHICAGO
" » How to detect images loaded in React." Alejandro Martinez | Sciencx - Accessed . https://www.scien.cx/2021/10/05/how-to-detect-images-loaded-in-react/
IEEE
" » How to detect images loaded in React." Alejandro Martinez | Sciencx [Online]. Available: https://www.scien.cx/2021/10/05/how-to-detect-images-loaded-in-react/. [Accessed: ]
rf:citation
» How to detect images loaded in React | Alejandro Martinez | Sciencx | https://www.scien.cx/2021/10/05/how-to-detect-images-loaded-in-react/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.