@figliolia/size-observer
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

Size Observer

Resize Observers simplified!

Installation

npm i @figliolia/size-observer
# or
yarn add @figliolia/size-observer

Vanilla

import { SizeObserver } from "@figliolia/size-observer";

const node = document.getElementById("myNode");

const observer = new SizeObserver(node, {
  width: true, // set to false to disable observing width
  height: true, // set to false to disable observing height
  type: "border-box", // (border-box, "content-box", "device-pixels")
  onChange: ({ height, width }) => {
    // your logic
  }
});

// Clean Up
observer.destroy();

React

This library also exports a useSizeObserver hook that you can use in your react components. The Hook returns a ref that you can attach to any DOM node and it'll be observed as long as it's mounted to the DOM

import { useMemo } from "react";
import { useSizeObserver } from "@figliolia/size-observer";

export const MyComponent = () => {

  // Declare your options
  const options = useMemo(() => ({
    width: true,
    height: true,
    type: "border-box",
    onChange: ({ width, height }) => {}
  }), []);

  // Create Your Ref
  const nodeRef = useResizeObserver(options);

  return (
    // Attach your ref!
    <div ref={nodeRef}>
      {/* Your Markup */}
    </div>
  );
}

Package Sidebar

Install

npm i @figliolia/size-observer

Weekly Downloads

14

Version

1.0.3

License

none

Unpacked Size

16 kB

Total Files

20

Last publish

Collaborators

  • alexfigliolia