hooks [RFC] useMeasures

o2g1uqev  于 2022-10-25  发布在  其他
关注(0)|答案(1)|浏览(167)

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 uses target and returns clientHeight and clientWidth only
  • useMeasures uses contentRect 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>
  );
};

I've already opened a PR with this functionality:
#1874

Detailed spec

Params

PropertyDescriptionTypeDefault
targetDOM element or ref objectElement | () => Element | MutableRefObject<Element> | null-

Result

PropertyDescriptionTypeDefault
xView value x of the elementnumber0
yView value y of the elementnumber0
topPosition top of the elementnumber0
rightPosition right of the elementnumber0
bottomPosition bottom of the elementnumber0
leftPosition left of the elementnumber0
widthThe width of the elementnumber0
heightThe height of the elementnumber0
balp4ylt

balp4ylt1#

My suggestion is to extend useSize,,api like: const { width, height, contentRect } = useSize() ,rename useSize and API while waiting for v4

相关问题