본문으로 건너뛰기

useImageOnLoad

Indicates whether the image has been loaded.

When ready, the state isLoaded changes to true.

Loaded: loading...

Reactive Adapter

const REACTIVE_ADAPTER = ({ onInit, onDestroy, getProps }) => {
const obj = reactive({ isLoaded: false });
const ref = getProps().ref;

const onLoaded = () => {
const element = ref.value || ref.current;

obj.isLoaded = !!(element.naturalWidth && element.complete);
};
onInit(() => {
const element = ref.value || ref.current;

element?.addEventListener("load", onLoaded);
onLoaded();
});

onDestroy(() => {
const element = ref.value || ref.current;

element?.removeEventListener("load", onLoaded);
});
return obj;
};

Frameworks

You can create a Reactive Component by importing the @cfcs/react module and using the useReactive function.

import React from "react";
import { useReactive } from "@cfcs/react";

function useImageOnLoad() {
const ref = React.useRef(null);

return Object.assign(useReactive(REACTIVE_ADAPTER, () => ({ ref })), {
ref,
});
}
export function App() {
const { isLoaded, ref } = useImageOnLoad();

return <div>
Loaded: {isLoaded ? "loaded" : "loading..."} <br />
<img src="your image src" ref={ref} />
</div>;
}