Skip to content

useElementBounding

Category
Export Size
1.07 kB
Last Changed
5 days ago

Reactive bounding box of an HTML element

Demo

Usage

tsx
import { 
useElementBounding
} from '@reause/core'
import {
useRef
} from 'react'
const
el
=
useRef
<HTMLDivElement | null>(null)
const {
x
,
y
,
top
,
right
,
bottom
,
left
,
width
,
height
} =
useElementBounding
(
el
)

The bounding box updates as the element is resized, scrolled or restyled:

tsx
import { 
useElementBounding
} from '@reause/core'
import {
useRef
} from 'react'
const
el
=
useRef
<HTMLTextAreaElement | null>(null)
const {
width
,
height
,
update
} =
useElementBounding
(
el
)
// <div> // <textarea ref={el} style={{ resize: 'both', overflow: 'hidden' }} /> // Width: {width}, Height: {height} // <button onClick={update}>Re-measure</button> // </div>

Call update() to re-measure on demand, e.g. after a synchronous layout change.

Type Declarations

ts
export interface UseElementBoundingOptions extends ConfigurableWindow {
    reset?: boolean;
    windowResize?: boolean;
    windowScroll?: boolean;
    immediate?: boolean;
    updateTiming?: 'sync' | 'next-frame';
}

export interface UseElementBoundingReturn {
    height: number;
    bottom: number;
    left: number;
    right: number;
    top: number;
    width: number;
    x: number;
    y: number;
    update: () => void;
}

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

export type ElementTargetOrArray<T extends TargetElement = TargetElement> = ElementTarget<T> | ElementTarget<T>[]

export function useElementBounding(target: ElementTarget, options?: UseElementBoundingOptions): UseElementBoundingReturn

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
8fddc - chore!: remove all Vue-only Maybe* types and getter unions, adopt React Ref (#462)

Released under the MIT License. v0.1.8