Skip to content

Instantly share code, notes, and snippets.

@LishuGupta652
Created December 27, 2021 08:36
Show Gist options
  • Save LishuGupta652/047c81c3fe54f5a98ecf5104e54fedf8 to your computer and use it in GitHub Desktop.
Save LishuGupta652/047c81c3fe54f5a98ecf5104e54fedf8 to your computer and use it in GitHub Desktop.
use Element Position React gist
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