DocsCloud UI HooksuseElementSize

useElementSize

Returns element width and height and observes changes with ResizeObserver.

Import

import { useElementSize } from '@tidbcloud/uikit'

Usage

useElementSize is a simpler version of useResizeObserver hook. It returns a ref object that should be passed to the observed element, and the element’s height and width.

import { useElementSize } from '@tidbcloud/uikit'
 
function Demo() {
  const { ref, width, height } = useElementSize()
 
  return (
    <>
      <textarea ref={ref} style={{ width: 400, height: 200 }}>
        Resize this element
      </textarea>
      <div>
        Width: {width}, Height: {height}
      </div>
    </>
  )
}

API

On the first render (as well as during SSR), or when no element is being observed, width and height properties are equal to 0.

import { useElementSize } from '@tidbcloud/uikit'
 
const { ref, width, height } = useElementSize()

Definition

function useElementSize<T extends HTMLElement = any>(): {
  ref: React.RefObject<T>
  width: number
  height: number
}