New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

react-use-rect

Package Overview
Dependencies
Maintainers
0
Versions
28
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-use-rect

Hook that is aiming to help you on tracking a DOM element boundaries

2.0.6
latest
Source
npm
Version published
Weekly downloads
1K
-27.17%
Maintainers
0
Weekly downloads
 
Created
Source

react-use-rect

Utility hook that aims to help with tracking an element's bounding client rect.

It might be found useful for simple cases such as getting element's size and position once it mounts to the DOM. As well as for complex ones when an element position changes frequently and needs to be tracked down (e.g. dropdowns and tooltips).

Installation

For npm users:

npm i react-use-rect

For Yarn users:

yarn add react-use-rect

Usage

Let's examine a very simple case at first.

import { useState } from 'react';
import { Rect, useRect } from 'react-use-rect';

function Example() {
  const [rect, setRect] = useState<Rect | null>(null);
  const [rectRef] = useRect(setRect);

  return <div ref={rectRef}>{rect && `This div is ${rect.width}px wide.`}</div>;
}

This hook doesn't make assumptions on how you'd like to manage a rect data: save it as a state, put it into a ref or not to store it at all.

In the example above we save our rect into a local state so we use the useState hook. However, it's possible to pass your own function to handle rect changes. Let's call it dispatchChange function.

const [rectRef] = useRect((rect) => console.log(rect.top));
return <div ref={rectRef} />;

The hook revalidates an element's bounding rect on every render but it calls dispatchChange only when the element's rect has changed.

Resize

You may want to revalidate the rect when the element's size chages not as a consequence of rendering (e.g. textarea being resized by a user).

In order to cover this need the resize option is introduced.

useRect(dispatchChange, { resize: true });

In the following example we'll be watching a textarea resize. Once it being resized we update styles of another element according to the textarea's rect.

import { useRef } from 'react';
import { useRect } from 'react-use-rect';

function Example2() {
  const rulerRef = useRef(null);
  const [rectRef] = useRect(
    (rect) => {
      if (rulerRef.current) {
        rulerRef.current.style.top = `${rect.top + rect.height + 10}px`;
        rulerRef.current.style.left = `${rect.left}px`;
        rulerRef.current.style.width = `${rect.width}px`;
      }
    },
    { resize: true }
  );

  return (
    <div>
      <div
        ref={rulerRef}
        style={{
          position: 'fixed',
          height: 2,
          background: 'red'
        }}
      />
      <textarea ref={rectRef} />
    </div>
  );
}

Scroll

It's also possible to revalidate a rect when a user scrolled the document, or some transition ended or something else happend and you want to be sure the rect is updated. Just call the revalidate function manually.

const [rectRef, revalidate] = useRect(dispatchChange);
revalidate();

Note that both rectRef and revalidate functions a referentially stable and never change during a component lifetime.

If you want dispatchChange to be called regardless the rect has changed or not, use the force option.

revalidate({ force: true });

There is also a one tiny hook included that could come in handy – useWindowOn. You can use it to add an event listener to the window and then revalidate a rect once the event captured.

import { useState } from 'react';
import { useRect, useWindowOn } from 'react-use-rect';

function Example3() {
  const [top, setTop] = useState<number | null>(null);
  const [rectRef, revalidate] = useRect((rect) => setTop(rect.top));
  useWindowOn('scroll', () => revalidate());

  return (
    <div style={{ height: '200vh' }}>
      <div ref={rectRef} style={{ marginTop: 100 }}>
        {top !== null && `I'm ${top}px from top.`}
      </div>
    </div>
  );
}

Reference

interface UseRect {
  (dispatchChange: DispatchChange, options?: Options): Result;
}

interface DispatchChange {
  (rect: Rect): void;
}

interface Rect {
  bottom: number;
  height: number;
  left: number;
  right: number;
  top: number;
  width: number;
  x: number;
  y: number;
}

interface Options {
  resize?: boolean;
}

type Result = [SetElement, Revalidate];

interface SetElement {
  (element: Element | null): void;
}

interface Revalidate {
  (options?: RevalidateOptions): void;
}

interface RevalidateOptions {
  force?: boolean;
}

interface UseWindowOn<T extends keyof WindowEventMap> {
  (eventType: T, callback: (event: WindowEventMap[T]) => void): void;
}

Keywords

react

FAQs

Package last updated on 29 Aug 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts