🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
Book a DemoInstallSign in
Socket

react-use-rect

Package Overview
Dependencies
Maintainers
1
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.0-alpha.3
Source
npm
Version published
Weekly downloads
2.2K
-22.21%
Maintainers
1
Weekly downloads
 
Created
Source

react-use-rect

This hook aims to help you on tracking a DOM element bounding rect.

It could be useful no matter you want just get an element's size and position once it mounts to the DOM, or build a complex logic for tooltips, popovers and other fancy UI stuff.

Getting started

Install a package into your project.

npm i react-use-rect

And for Yarn users.

yarn add react-use-rect

Let's create a simple component that uses a useRect hook.

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

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

  return (
    <div ref={rectRef}>{rect && <span>I'm ${rect.width}px wide!</span>}</div>
  );
}

If you want to keep track on an element's size change you may use resize option.

useRect(setRect, { resize: true });

Well, resize is the one and the only option supported.

Updating a bounding rect

There a certain scenarios when you may want to re-measure a bounding rect. And it tries to cover them all introducing revalidateRect function as well as useWindowOn hook which simplifies adding an event listener to a window.

Let's take a closer look at it.

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

function Example2() {
  const [rect, setRect] = useState<Rect | undefined>();
  const [rectRef, revalidateRect] = useRect(setRect);
  useWindowOn('scroll', revalidateRect);

  return (
    <div ref={rectRef}>
      {rect && (
        <span>
          Passing coordinates: [${rect.left}, ${rect.top}px].
        </span>
      )}
    </div>
  );
}

The component we've created above will update the coordinates it shows whenever it's bounding rect changes after a document or any of it's drescendant elements scrolls.

You can call revalidateRect manually when you want to re-measure an element's bounding rect and if it changed you'll know it.

Keywords

react

FAQs

Package last updated on 27 Apr 2022

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