useBoundingRect
function useBoundingRect(
element,
updateOnWindowResize,
windowResizeThrottle): DOMRect | undefined;
Observes a HTMLElement and returns its bounding rect. Updates when the element's size changes.
If a ref to a HTMLElement is passed and ref.current is null it polls the ref to detect when the HTMLElement value gets assigned to ref.current, this is useful in case the Component using this hook does not rerender when ref.current changes.
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
element | HTMLElement | RefObject<HTMLElement | null>` \ | null | undefined |
updateOnWindowResize | boolean | false | Whether to update the rect on window resize (default: false) |
windowResizeThrottle | number | 0 | Throttle interval in ms for window resize updates (default: 0) |
Returns
DOMRect | undefined
The DOMRect of the element, or undefined if element is not available
Example
const ref = useRef<HTMLDivElement>(null);
const rect = useBoundingRect(ref);
const [element, setElement] = useState<HTMLDivElement | null>(null);
const rect2 = useBoundingRect(element);
// Update on window resize with 150ms throttle
const rect3 = useBoundingRect(ref, true, 150);