You can create a custom hook in React to get the bounds of an element that is passed as a ref
to your component as shown below:
788 chars38 lines
First, we define the Bounds
type which represents the dimensions and position of the element. We also define a UseBoundsProps
type which takes a ref
property that is a RefObject
to the element that we want to get its bounds.
Then, we define the useBounds
function which takes the ref
as a parameter and returns the Bounds
object or null
if the element hasn't been mounted yet.
Inside the useEffect
hook, we define a getElementBounds
function that gets the initial bounds of the element and updates the bounds
state. We also register a window
resize
event listener to keep the bounds
state updated if the window is resized. We also clean up the event listener when the ref
is unmounted.
Finally, we return the bounds
object from the hook.
To use this hook in a component, simply pass the ref
of the element you want to get its bounds to the useBounds
hook as shown below:
216 chars14 lines
In the above example, we create a ref
with a useRef
hook and pass it to the useBounds
hook via an object with a ref
property. We then attach the ref
to the div
element that we want to get its bounds. The bounds
object can now be used in the component's render function.
gistlibby LogSnag