Measure DOM nodes using a React Hook.
npm install use-measurer --save
useMeasure receives a key array with the following possible options.
The first value returned by the hook is an object, here are the measured properties.
Example
const [measuring, ...] = useMeasure(["client", "margin", ...]);
const { client, margin } = measuring;
Note: the initial value of the measurements is an empty object
Adds the following to client
returned in the first value of the array.
clientTop, clientLeft, clientWidth, and clientHeight.
Adds the following to offset
returned in the first value of the array.
offsetTop, offsetLeft, offsetWidth, and offsetHeight.
Adds the following to scroll
returned in the first value of the array.
scrollTop, scrollLeft, scrollWidth, and scrollHeight.
Uses
getBoundingClientRect
to calculate the element rect and add it to bounds
returned in the first value of the array.
Uses
getComputedStyle
to calculate margins and add it to margin
returned in the first value of the array.
import React from "react";
import useMeasurer from "use-measurer";
function MyComponent(){
const [measuring, nodeRef, forceMeasurementFn] = useMeasurer(["client","margin"]);
return (
<div ref={nodeRef} style={{ margin: 10, width: '100%', maxWidth: 500, height: 100, border: '2px solid black' }}>
<code>{JSON.stringfy(measuring)}</code>
{measuring.client?.width > 300 ? <span>The managed node</span> : null}
</div>
)
}
export default MyComponent;