Appearance
useElementBounding
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