Hook that listens for bounding box changes on a DOM element.
✓ Published0🌍 Public
Aabonello
Last edited Sep 29, 2021
Created on Dec 30, 2021
This example shows a React hook that tracks the bounding box of a DOM element and returns its updated width, height, x, and y coordinates. It uses the native `ResizeObserver` API to listen for size changes and `getBoundingClientRect()` to capture the element’s position and dimensions. The hook stores the rectangle in React state via `useState` and updates it through a `useEffect` that observes the element referenced by a `MutableRefObject`. The code is written in TypeScript and defines a `toRect` helper to normalize the `DOMRect` output, ensuring default values when the element is not yet available.
AI-generated description