Skip to content

Instantly share code, notes, and snippets.

@busypeoples
Last active May 14, 2021 17:03
Show Gist options
  • Save busypeoples/ea4758db71984a8d771dbb46a68e0115 to your computer and use it in GitHub Desktop.
Save busypeoples/ea4758db71984a8d771dbb46a68e0115 to your computer and use it in GitHub Desktop.
Preact hook for useInView

useInView Preact Hook

Can be used as a starting point for implementing your own specific check to see if an element is in view.

const YourViewComponent = () => {
  const { isInView, inViewRef } = useInView();

  return (
    <div ref={inViewRef} className={isInView ? 'inViewClass' : 'outOfViewClass'}>
      Some content
    </div>
  );
};
import { useEffect, useState, useRef } from 'preact/hooks';
const isElementVisible = (element: HTMLElement) => {
if (!element) {
return false;
}
const rect = element.getBoundingClientRect();
const width = window.innerWidth || document.documentElement.clientWidth;
const height = window.innerHeight || document.documentElement.clientHeight;
return !(rect.right < 0 || rect.bottom < 0 || rect.left > width || rect.top > height);
};
const useInView = () => {
const ref = useRef<HTMLDivElement | null>(null);
const [isInView, setIsInView] = useState(false);
useEffect(() => {
if (ref.current !== null) {
setIsInView(isElementVisible(ref.current));
}
const onScroll = () => {
if (ref.current) {
setIsInView(isElementVisible(ref.current));
}
};
window.addEventListener('scroll', onScroll);
return () => window.removeEventListener('scroll', onScroll);
}, [ref]);
const inViewRef = (node: HTMLDivElement | null) => {
ref.current = node;
};
return { isInView, inViewRef };
};
export default useInView;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment