Files
outline/app/hooks/useOnScreen.ts
Tom Moor 5977fe4caa fix: Editor title does not autoFocus on first load (#3238)
* fix: Editor title does not autoFocus on first load

* Detect IntersectionObserver for IE support
2022-03-13 22:08:26 -07:00

35 lines
849 B
TypeScript

import * as React from "react";
/**
* Hook to return if a given ref is visible on screen.
*
* @returns boolean if the node is visible
*/
export default function useOnScreen(ref: React.RefObject<HTMLElement>) {
const isSupported = "IntersectionObserver" in window;
const [isIntersecting, setIntersecting] = React.useState(!isSupported);
React.useEffect(() => {
const element = ref.current;
let observer: IntersectionObserver | undefined;
if (isSupported) {
observer = new IntersectionObserver(([entry]) => {
// Update our state when observer callback fires
setIntersecting(entry.isIntersecting);
});
}
if (element) {
observer?.observe(element);
}
return () => {
if (element) {
observer?.unobserve(element);
}
};
}, []);
return isIntersecting;
}