use-element-in-view
Version:
A simple React hook to track whether an element is visible in the viewport with the Intersection Observer. This API provides a native way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-leve
3 lines (2 loc) • 1.88 kB
JavaScript
Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react");exports.useElementInView=function(n){var r,t,u=void 0===n?{}:n,o=u.ref,i=void 0===o?null:o,c=u.root,s=void 0===c?null:c,l=u.rootMargin,a=void 0===l?"0px":l,f=u.threshold,d=void 0===f?0:f,v=u.defaultInView,y=u.disconnectOnceVisible,w=void 0!==y&&y,b=u.onChange,p=e.useState({entry:void 0,elementInView:void 0!==v&&v}),I=p[0],m=p[1],h=e.useRef(null),R=e.useRef(null),g=e.useRef(null),V=e.useRef(!1),O=((t=e.useRef(r=b)).current=r,t),C=e.useMemo((function(){return Array.isArray(d)?d.join():d}),[d]),E=e.useCallback((function(e){!V.current&&h.current&&(V.current=!0,h.current.observe(e))}),[]),M=e.useCallback((function(){V.current&&h.current&&(h.current.disconnect(),h.current=null,V.current=!1,g.current=null)}),[]),k=e.useCallback((function(){if("undefined"!=typeof window&&"IntersectionObserver"in window&&"IntersectionObserverEntry"in window&&"intersectionRatio"in IntersectionObserverEntry.prototype){var e,n=null;if(R.current?n=R.current:i instanceof HTMLElement?n=i:(e=i)&&"object"==typeof e&&"current"in e&&(n=i.current),g.current!==n)if(g.current=n,n){var r="string"==typeof C?C.split(",").map((function(e){return parseFloat(e)})):C;if(!h.current){var t=new IntersectionObserver((function(e){var n=e[0],r=n.isIntersecting&&t.thresholds.some((function(e){return n.intersectionRatio>=e}));r&&w&&M(),O.current?O.current(n):m({entry:n,elementInView:r})}),{root:s,rootMargin:a,threshold:r});h.current=t}E(n)}else console.warn("🚨 No element has been found, are you sure you correctly assigned a ref?")}}),[s,a,C,w,E,M,i,O]),j=e.useCallback((function(e){e&&(R.current=e,k())}),[k]);return e.useEffect((function(){return i&&k(),function(){M()}}),[i,k,M]),{entry:I.entry,inView:I.elementInView,assignRef:j,disconnect:M}};
//# sourceMappingURL=use-element-in-view.cjs.production.min.js.map
;