@charlietango/use-element-size

Measure the size of a DOM element using ResizeObserver

Usage no npm install needed!

<script type="module">
  import charlietangoUseElementSize from 'https://cdn.skypack.dev/@charlietango/use-element-size';
</script>

README

useElementSize

Measure the size of a DOM element using ResizeObserver

Checkout the Storybook demo.

Installation

yarn add @charlietango/use-element-size

API

const [ref, size] = useElementSize()

The hook returns an Array with a ref function, and the measured size. Assign the ref to the element you want to measure.

Example

import React from 'react'
import useElementSize from '@charlietango/use-element-size'

const Component = () => {
  const [ref, size] = useElementSize()
  return (
    <div ref={ref}>
      <pre>
        <code>{JSON.stringify(size, null, 2)}</code>
      </pre>
    </div>
  )
}

export default Component