Skip to main content

useElementSize

Get DOM element size.

API

function useElementSize(target: EffectTarget<Element>): {
width: number | undefined;
height: number | undefined;
};

type Nullable<T> = T | undefined | null;
type EffectTarget<T> =
| Nullable<T>
| (() => Nullable<T>)
| { current: Nullable<T> };

Params:

  • target: A DOM element. It can be undefined, null, a DOM element, a ref object references a DOM element, or a function returns a DOM element.

Results:

  • width: Element width.
  • height: Element height.

Example

You can change the browser window size to see the effect.

Element size: {"width":0,"height":0}
import React, { useRef } from "react";
import { useElementSize } from "@lilib/hooks";

function Example() {
const ref = useRef(null);
const { width = 0, height = 0 } = useElementSize(ref);

return (
<div
ref={ref}
style={{
padding: 16,
border: "1px solid rgba(128, 128, 128, 0.25)",
}}
>
Element size: {JSON.stringify({ width, height })}
</div>
);
}

export default Example;