useMeasures
Description
I'd like to introduce quite commonly used in other libraries of that type functionality of gathering target element relative measurement properties. It is similar to useSize
, but it differs in the source of truth and returns more target element properties.
useSize
usestarget
and returnsclientHeight
andclientWidth
onlyuseMeasures
usescontentRect
and returns all described below properties
API
// from src/utils/domTarget.ts
type BasicTarget<T extends TargetType = Element> =
| (() => TargetValue<T>)
| TargetValue<T>
| MutableRefObject<TargetValue<T>>;
interface UseMeasuresRes {
readonly top: number;
readonly right: number;
readonly bottom: number;
readonly left: number;
readonly x: number;
readonly y: number;
readonly height: number;
readonly width: number;
}
type UseMeasures = (target: BasicTarget) => UseMeasuresRes
DEMO
export default () => {
const ref = useRef(null); // we can either use Element instead of ref e.g. document.querySelector('body')
const { height, width, top, left, x, y, right, bottom } = useMeasures(ref);
return (
<div ref={ref}>
<p>Try to scroll or resize the preview window </p>
<p>x: {x}</p>
<p>y: {y}</p>
<p>top: {top}</p>
<p>right: {right}</p>
<p>bottom: {bottom}</p>
<p>left: {left}</p>
<p>width: {width}</p>
<p>height: {height}</p>
</div>
);
};
Related PRs
I've already opened a PR with this functionality:
#1874
Detailed spec
Params
Property | Description | Type | Default |
---|---|---|---|
target | DOM element or ref object | Element | () => Element | MutableRefObject<Element> | null | - |
Result
Property | Description | Type | Default |
---|---|---|---|
x | View value x of the element | number | 0 |
y | View value y of the element | number | 0 |
top | Position top of the element | number | 0 |
right | Position right of the element | number | 0 |
bottom | Position bottom of the element | number | 0 |
left | Position left of the element | number | 0 |
width | The width of the element | number | 0 |
height | The height of the element | number | 0 |
1条答案
按热度按时间balp4ylt1#
My suggestion is to extend useSize,,api like:
const { width, height, contentRect } = useSize()
,rename useSize and API while waiting for v4