2.1.0 • Published 6 months ago

@figliolia/size-observer v2.1.0

Weekly downloads
-
License
-
Repository
github
Last release
6 months ago

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 = () => {
  // Create Your Ref
  const nodeRef = useResizeObserver<HTMLDivElement>({
    width: true,
    height: true,
    type: "border-box",
    onChange: ({ width, height }) => {
      // do something with the observed dimensions
    }
  });

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

10 months ago

2.1.0

6 months ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago