npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-use-rect

v2.0.4

Published

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

Downloads

3,446

Readme

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;
}