Created
December 27, 2021 08:36
-
-
Save LishuGupta652/047c81c3fe54f5a98ecf5104e54fedf8 to your computer and use it in GitHub Desktop.
use Element Position React gist
This file contains 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 { useEffect } from "react"; | |
import { useState } from "react"; | |
export default function useElementPosition(el) { | |
function getElement(x, y) { | |
return { | |
x, | |
y, | |
}; | |
} | |
const [elementPosition, setElementPosition] = useState(getElement()); | |
useEffect(() => { | |
function handlePosition() { | |
let element = el.current; | |
let x = | |
element.getBoundingClientRect().left + | |
document.documentElement.scrollLeft + | |
element.offsetWidth / 2; | |
let y = | |
element.getBoundingClientRect().top + | |
document.documentElement.scrollTop + | |
element.offsetHeight / 2; | |
setElementPosition(getElement(x, y)); | |
} | |
handlePosition(); | |
}, [el]); | |
return elementPosition; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment