Docs
Measure
Measure
Effortlessly measure and track your component’s dimensions
About
The useMeasure hook monitors and responds to changes in the size of a React component. It uses the ResizeObserver API to track changes in the component’s dimensions (width and height) and keeps them available as state. The returned ref is used on the element whose dimensions you want to measure, making it valuable for responsive design and dynamic layout adjustments.
Return Values
| Name | Type | Description |
|---|---|---|
| ref | React ref object | A React reference that can be attached to a DOM element to observe. |
| rect | object | An object containing the width and height of the observed element. |
Rect Object Properties
| Property | Type | Description |
|---|---|---|
| width | number | Width of the observed element. |
| height | number | Height of the observed element. |
Installation
Run the following command:
npx scriptkavi-hooks@latest add measureUsage
import { useMeasure } from "@/hooks/measure"import * as React from "react"
function Measure({ type = "horizontal" }) {
const [ref, { width, height }] = useMeasure()
return (
<figure>
<figcaption>
<span>{type}</span>
</figcaption>
<article
ref={ref}
className={type}
style={{
resize: type,
}}
>
{type === "horizontal" ? (
<label>width: {Math.floor(width)}</label>
) : (
<label>height: {Math.floor(height)}</label>
)}
</article>
</figure>
)
}
export default function App() {
return (
<section>
<h1>useMeasure</h1>
<p>(Resize the rulers)</p>
<Measure />
</section>
)
}