ahooks
Version:
react hooks library
30 lines (29 loc) • 1.44 kB
JavaScript
import { __rest } from "tslib";
import { useState } from 'react';
import { getTargetElement } from '../utils/domTarget';
import useEffectWithTarget from '../utils/useEffectWithTarget';
function useInViewport(target, options) {
const _a = options || {}, { callback } = _a, option = __rest(_a, ["callback"]);
const [state, setState] = useState();
const [ratio, setRatio] = useState();
useEffectWithTarget(() => {
const targets = Array.isArray(target) ? target : [target];
const els = targets.map((element) => getTargetElement(element)).filter(Boolean);
if (!els.length) {
return;
}
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
setRatio(entry.intersectionRatio);
setState(entry.isIntersecting);
callback === null || callback === void 0 ? void 0 : callback(entry);
}
}, Object.assign(Object.assign({}, option), { root: getTargetElement(options === null || options === void 0 ? void 0 : options.root) }));
els.forEach((el) => observer.observe(el));
return () => {
observer.disconnect();
};
}, [options === null || options === void 0 ? void 0 : options.rootMargin, options === null || options === void 0 ? void 0 : options.threshold, callback], target);
return [state, ratio];
}
export default useInViewport;