Skip to content

Instantly share code, notes, and snippets.

@smashingpat
Created February 6, 2019 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smashingpat/c22036c340419b01cbf92b94577d07d5 to your computer and use it in GitHub Desktop.
Save smashingpat/c22036c340419b01cbf92b94577d07d5 to your computer and use it in GitHub Desktop.
import * as React from "react";
import useBoundingRef from "./useBoundingRect";
function App() {
const elementRef = React.useRef<HTMLDivElement | null>(null);
const bounds = useBoundingRef(elementRef);
return (
<div ref={elementRef}>
Get my bounds!
</div>
);
}
import * as React from "react";
interface Bounds {
offsetTop: number;
offsetLeft: number;
offsetWidth: number;
offsetHeight: number;
element: HTMLElement;
}
export default function withBoundingRect(elRef: React.RefObject<HTMLElement | null>) {
const [bounds, setBounds] = React.useState<Bounds | null>(null);
const lastEl = React.useRef<HTMLElement | null>(elRef.current);
React.useEffect(() => {
const element = elRef.current;
if (element) {
if (element !== lastEl.current) {
setBounds({
offsetTop: element.offsetTop,
offsetLeft: element.offsetLeft,
offsetWidth: element.offsetWidth,
offsetHeight: element.offsetHeight,
element,
});
}
} else if (bounds !== null) {
setBounds(null);
}
lastEl.current = element;
});
return bounds;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment