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 error
events, 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;
};