useElementSize
This hook provides a convenient way to track and retrieve the size of a DOM element in real-time. It utilizes the ResizeObserver API to monitor size changes efficiently.
Usage
-
Make sure you have
@ridgehkr/useful
installed in your application. If not, you can get started by following the installation instructions. -
Import
useElementSize
into your component.
import { useElementSize } from '@ridgehkr/useful'
Example
This hook takes a single argument, a React ref (opens in a new tab) pointing to the DOM element you want the sizing information of. It returns an object containing the element's width
and height
.
Here's an example of how you can use useElementSize
in your React component:
import { useElementSize } from '@ridgehkr/useful'
function ResizingBox() {
const sizeRef = useRef<HTMLTextAreaElement>(null)
const { width, height } = useElementSize(sizeRef)
const [modSize, setModSize] = useState(200)
return (
<div>
<p>
<label>
Change box size:
<br />
<input
type='range'
min='100'
max='800'
value={modSize}
step='10'
onChange={(e: React.FormEvent<HTMLInputElement>) =>
setModSize(parseInt(e.currentTarget.value))
}
/>
</label>
</p>
<textarea
style={{
width: modSize,
height: modSize,
margin: '0 auto',
border: '1px solid black',
backgroundColor: '#cfcfcf',
resize: 'both',
}}
ref={sizeRef}
/>
<h2>Box size:</h2>
<p>
width: <code>{width}</code>
<br />
height: <code>{height}</code>
</p>
</div>
)
}
API Reference
Hook Signature
useElementSize(ref: React.RefObject<HTMLElement>): ElementSize
Parameters
The useElementSize
hook takes a single argument, a React ref (opens in a new tab) that points to the DOM element you want to monitor for size changes.
Parameter | Type | Required? | Description |
---|---|---|---|
ref | React.RefObject<HTMLElement> | true | A ref of the DOM element to get the size of. |
Return Value
The hook returns a ElementSize
object with the following properties:
Property | Type | Description |
---|---|---|
width | number | The current width in pixels of the monitored element |
height | number | The current height in pixels of the monitored element |
A note on width
and height
These values represent the offsetWidth (opens in a new tab) and offsetHeight (opens in a new tab) dimensions of the element's content box. This is the area inside of the element's padding and border, while ignoring any pseudo-elements.