react-use-measure

repository·master·Indexed 21 days ago

https://github.com/pmndrs/react-use-measure

A reactive utility for measuring the boundaries (width, height, top, left, etc.) of DOM elements. It provides the useMeasure hook to track dimensions and positions while accounting for viewport, page, and nested scroll offsets. Version 2.1.7 supports options for debouncing, ResizeObserver polyfills, and offsetSize measurements.

Tokens
1.3K
Snippets
5
Records
8
Agent score
26%

What's inside react-use-measure

  1. Handling multiple refs on a single element

    master
    Because useMeasure returns its own ref (to handle unmount tracking via functional refs), you cannot directly use your own ref on the same element. To use both the useMeasure ref and a custom ref on the same element, use a utility like react-merge-refs.
  2. Inject a ResizeObserver polyfill

    master

    The library relies on the ResizeObserver API. If you are targeting environments that do not support it, you can inject a polyfill (such as @juggle/resize-observer) via the polyfill option to avoid polluting the global window object.

    import { ResizeObserver } from '@juggle/resize-observer'
    
    function App() {
      const [ref, bounds] = useMeasure({ polyfill: ResizeObserver })
      // ...
    }
  3. Use the useMeasure hook

    master

    The useMeasure hook provides a ref to attach to an element and a bounds object containing its reactive dimensions and position.

    Note: Because measurement occurs after the element renders, the bounds will contain zero values on the initial render and will be updated in subsequent renders once the measurement is complete.

    import useMeasure from 'react-use-measure'
    
    function App() {
      const [ref, bounds] = useMeasure()
    
      // consider that knowing bounds is only possible *after* the view renders
      // so you'll get zero values on the first run and be informed later
    
      return <div ref={ref} />
    }
  4. useMeasure API reference

    master

    The useMeasure hook accepts an optional Options object and returns a tuple containing a ref and a RectReadOnly object.

    Signature

    useMeasure(
      options: Options = { debounce: 0, scroll: false }
    ): [React.MutableRefObject<HTMLElement | SVGElement>, RectReadOnly]

    Options

    OptionTypeDescription
    debouncenumber or { scroll: number; resize: number }Debounce events in milliseconds.
    scrollbooleanIf true, the hook reacts to nested scroll changes. Set to false if your view is static.
    polyfill{ new (cb: ResizeObserverCallback): ResizeObserver }Inject a ResizeObserver polyfill.
    offsetSizebooleanIf true, measures size using offsetHeight and offsetWidth to ignore parent scale transforms.

    Return Value: RectReadOnly

    An object containing the following read-only properties:

    • x: number
    • y: number
    • width: number
    • height: number
    • top: number
    • right: number
    • bottom: number
    • left: number
  5. Configure useMeasure options

    master

    The useMeasure hook accepts an Options object to customize measurement behavior:

    • debounce: A number (ms) or an object { scroll: number; resize: number } to debounce measurement updates for scroll and resize events respectively.
    • scroll: A boolean. If true, the hook will also listen to scroll events on the element's scroll containers and the window to update measurements.
    • polyfill: A constructor for a ResizeObserver polyfill to be used if the browser does not support it natively.
    • offsetSize: A boolean. If true, the hook uses offsetHeight and offsetWidth for height and width instead of getBoundingClientRect() (only applies to HTMLElement).
    const [ref, bounds] = useMeasure({
      debounce: { scroll: 100, resize: 200 },
      scroll: true,
      offsetSize: true
    })
  6. Use the useMeasure hook

    master

    The useMeasure hook provides a way to measure the bounding box of a DOM element. It returns a ref that you can attach to an element, the current bounding box (as a RectReadOnly object), and a function to manually trigger a measurement update.

    Usage

    import useMeasure from 'react-use-measure'
    
    function MyComponent() {
      const [ref, bounds, forceRefresh] = useMeasure()
    
      return (
        <div ref={ref}>
          I am {bounds.width}px wide and {bounds.height}px tall.
          <button onClick={forceRefresh}>Force Re-measure</button>
        </div>
      )
    }
    import useMeasure from 'react-use-measure'
    
    function MyComponent() {
      const [ref, bounds, forceRefresh] = useMeasure()
    
      return (
        <div ref={ref}>
          I am {bounds.width}px wide and {bounds.height}px tall.
          <button onClick={forceRefresh}>Force Re-measure</button>
        </div>
      )
    }
  7. The RectReadOnly type

    master

    The RectReadOnly type represents the measurement results. It contains the following read-only properties:

    • x: The x-coordinate of the top-left corner.
    • y: The y-coordinate of the top-left corner.
    • width: The width of the element.
    • height: The height of the element.
    • top: The distance from the top of the viewport to the top of the element.
    • right: The distance from the left of the viewport to the right of the element.
    • bottom: The distance from the top of the viewport to the bottom of the element.
    • left: The distance from the left of the viewport to the left of the element.