Clawscale

Resize sensor

A ResizeSensor calls onResize when its child element changes size. It wraps the browser's ResizeObserver API.

Usage#

import { ResizeSensor } from "@clawscale/react";
  • The child must be a single DOM element, or a component that forwards its ref to one.
  • If you attach your own ref to the child, pass the same ref as targetRef.
  • onResize runs asynchronously, at most once per frame.

Examples#

Observed width#

Drag the lower right corner of the box. onResize receives a list of ResizeObserverEntry objects. contentRect.width is the width inside the padding.

Observed width: measuring
import { ResizeSensor } from "@clawscale/react";
import { useState } from "react";

export default function ResizeSensorBasic() {
  const [width, setWidth] = useState<number>();
  return (
    <ResizeSensor onResize={(entries) => setWidth(entries[0]?.contentRect.width)}>
      <div
        style={{
          border: "1px dashed var(--cs-color-border-strong)",
          borderRadius: "var(--cs-radius-md)",
          maxWidth: "100%",
          minWidth: 160,
          overflow: "hidden",
          padding: 16,
          resize: "horizontal",
          width: 320,
        }}
      >
        Observed width: <strong>{width === undefined ? "measuring" : `${Math.round(width)} px`}</strong>
      </div>
    </ResizeSensor>
  );
}

Props interface#

interface ResizeSensorProps@clawscale/react

ResizeSensor requires a single DOM element child and will error otherwise.

PropsDescription
childrenrequired
React.JSX.Element
Single child, must be an element and not a string or fragment.
observeParents
boolean = false
If true, all parent DOM elements of the container will also be observed for size changes. The array of entries passed to onResize will now contain an entry for each parent element up to the root of the document.
onResizerequired
(entries: ResizeObserverEntry[]) => void
Callback invoked when the wrapped element resizes.
targetRef
React.RefObject<HTMLElement>
If you attach a ref to the child yourself when rendering it, you must pass the same value here (otherwise, ResizeSensor won't be able to attach its own).