Skip to content

useElementSize

Category
Export Size
1.02 kB
Last Changed
5 days ago

Reactive size of an HTML element. ResizeObserver MDN

Demo

Usage

tsx
import { 
useElementSize
} from '@reause/core'
import {
useRef
} from 'react'
const
el
=
useRef
<HTMLTextAreaElement | null>(null)
const {
width
,
height
,
stop
} =
useElementSize
(
el
)

The element's size updates as it is resized:

tsx
import { 
useElementSize
} from '@reause/core'
import {
useRef
} from 'react'
const
el
=
useRef
<HTMLDivElement | null>(null)
const {
width
,
height
} =
useElementSize
(
el
, {
width
: 0,
height
: 0 }, {
box
: 'border-box' })
// <div ref={el} style={{ resize: 'both', overflow: 'auto' }}> // Width: {width}, Height: {height} // </div>

The observer is disconnected automatically on unmount. Call stop() to disconnect earlier.

Type Declarations

ts
export interface ElementSize {
    width: number;
    height: number;
}

export interface UseElementSizeOptions extends UseResizeObserverOptions {
}

export interface UseElementSizeReturn {
    width: number;
    height: number;
    stop: () => void;
}

export interface UseResizeObserverOptions extends ResizeObserverOptions, ConfigurableWindow {
}

export type ElementTarget<T extends TargetElement = TargetElement> = RefObject<T | null>

export function useElementSize(target: ElementTarget, initialSize?: ElementSize, options?: UseElementSizeOptions): UseElementSizeReturn

export function useResizeObserver(target: ElementTargetOrArray, callback: ResizeObserverCallback, options?: UseResizeObserverOptions): UseResizeObserverReturn

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
e608a - feat(ci): align CI, packaging and release with VueUse
9dfff - fix(core): resolve useElementSize audit findings (#551)
8fddc - chore!: remove all Vue-only Maybe* types and getter unions, adopt React Ref (#462)

Released under the MIT License. v0.1.8