Skip to content

Commit

Permalink
useIntersectionObserverRef
Browse files Browse the repository at this point in the history
  • Loading branch information
imbhargav5 committed Oct 2, 2019
1 parent 3cd4dbf commit 32558c8
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
12 changes: 12 additions & 0 deletions packages/shared/useIntersectionObserverRef.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { HTMLElementOrNull } from "./utils";
/**
*
* useIntersectionObserverRef hook
*
* Returns a mutation observer for a React Ref and fires a callback
*
* @param {IntersectionObserverCallback} callback Function that needs to be fired on mutation
* @param {IntersectionObserverInit} options
*/
declare function useIntersectionObserverRef(callback: IntersectionObserverCallback, options?: IntersectionObserverInit): ((node: HTMLElementOrNull) => void)[];
export { useIntersectionObserverRef };
49 changes: 49 additions & 0 deletions packages/shared/useIntersectionObserverRef.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { useEffect, Ref, MutableRefObject, useCallback, useState } from "react";
import { HTMLElementOrNull } from "./utils";

var config: IntersectionObserverInit = {
root: null,
rootMargin: "0px 0px 0px 0px",
threshold: [0, 1]
};

/**
*
* useIntersectionObserverRef hook
*
* Returns a mutation observer for a React Ref and fires a callback
*
* @param {IntersectionObserverCallback} callback Function that needs to be fired on mutation
* @param {IntersectionObserverInit} options
*/
function useIntersectionObserverRef(
callback: IntersectionObserverCallback,
options: IntersectionObserverInit = config
) {
const { root = null, rootMargin, threshold } = {
...options
};

const [node, setNode] = useState<HTMLElementOrNull>(null);

useEffect(() => {
// Create an observer instance linked to the callback function
if (node) {
const observer = new IntersectionObserver(callback, options);

// Start observing the target node for configured mutations
observer.observe(node);
return () => {
observer.disconnect();
};
}
}, [node, callback, root, rootMargin, threshold]);

const ref = useCallback((node: HTMLElementOrNull) => {
setNode(node);
}, []);

return [ref];
}

export { useIntersectionObserverRef };

0 comments on commit 32558c8

Please sign in to comment.