Last active
May 22, 2021 21:21
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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