Track the size of a react-dom
element (without ResizeObserver
).
Only 540 bytes min+gzip!
import React from 'react'
import { useElementSize } from 'use-element-size'
const Example = () => {
const ref = useElementSize((size, prevSize, elem) => {
console.log({ size, prevSize, elem })
})
return (
<div
ref={ref}
style={{
position: 'relative',
width: '50%',
height: '50%',
}}
/>
)
}
-
⚠️ Be sure the tracked element never hasposition: static
. -
The
size
parameter isnull
when the tracked element is unmounted. -
The
prevSize
parameter isnull
when the tracked element was just mounted. -
Tracking stops when
useElementSize
is passedfalse/null/undefined
instead of a function. -
The callback waits until the next
requestAnimationFrame
tick before running. -
The
Size
andSizeCallback
types are exported for your convenience.
https://codesandbox.io/s/use-element-size-demo-dszk1?file=/src/index.tsx