useDimensions – a React Hook to measure DOM nodes

import React from 'react'
import useDimensions from 'react-use-dimensions'

const MeasuredNode = () => {
    const [ref, { x, y, width, height }] = useDimensions();

    return (
        <p ref={ref}>
            I am a paragraph at ({x}px, {y}px) position with a width of {width}px
            and height of {height}px
        </p>
    );
};

Handy. Uses window.resize+window.scroll internally, yet I’m quite sure it could be done using the more modern ResizeObserver+IntersectionObserver too.

useDimensions demo →
useDimensions Source (GitHub) →

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.