Skip to content

Instantly share code, notes, and snippets.

@celian-rib
Last active May 22, 2021 21:21
Show Gist options
  • Save celian-rib/f3a8ec4a80486b020ef3c7a4e2772835 to your computer and use it in GitHub Desktop.
Save celian-rib/f3a8ec4a80486b020ef3c7a4e2772835 to your computer and use it in GitHub Desktop.
React hook to know if an element is in the middle of the window.
import { useState, useEffect } from 'react';
/**
* Check is an HTML element is in the middle of the window
* @param ref The HTML element to check
* @param range The range in which that define the middle zone
* @returns true if the provided ref is in the middle of the window
*/
export default const useOnMiddleOfScreen = (ref: React.RefObject<HTMLDivElement>, range: number): boolean => {
const [isOnMiddle, setIsOnMiddle] = useState(false);
const { innerHeight: windowHeight } = window;
const refTop = ref.current?.getBoundingClientRect().top ?? 0;
const refHeight = ref.current?.getBoundingClientRect().height ?? 0;
useEffect(() => setIsOnMiddle(
(refTop + (refHeight / 2)) > (windowHeight / 2) - range && (refTop + (refHeight / 2)) < (windowHeight / 2) + range
), [refTop]);
return isOnMiddle;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment