UI & Layout
useBoundingclientrect
Returns the bounding client rect of a DOM element, updated on resize.
About
getBoundingClientRect hook for React.
Examples
Basic example
import { useBoundingclientrect } from "rooks";
import { useRef, useState } from "react";
function App() {
const myRef = useRef();
const getBoundingClientRect = useBoundingclientrect(myRef);
const [XOffset, setXOffset] = useState(0);
const [YOffset, setYOffset] = useState(100);
const displayString = JSON.stringify(getBoundingClientRect, null, 2);
return (
<>
<div
style={{
width: 300,
background: "lightblue",
padding: "10px",
position: "absolute",
left: XOffset,
top: YOffset,
}}
ref={myRef}
>
<div
style={{
resize: "both",
overflow: "auto",
background: "white",
color: "blue",
maxWidth: "100%",
}}
>
<p>
Resize this div as you see fit. To demonstrate that it also updates
on child dom nodes resize
</p>
</div>
<h2>Bounds</h2>
<p>
<button onClick={() => setXOffset(XOffset - 5)}> Move Left </button>
<button onClick={() => setXOffset(XOffset + 5)}> Move Right </button>
</p>
<p>
<button onClick={() => setYOffset(YOffset - 5)}> Move Up </button>
<button onClick={() => setYOffset(YOffset + 5)}> Move Down </button>
</p>
</div>
<div style={{ height: 500 }}>
<pre>{displayString}</pre>
</div>
</>
);
}
export default App;Read position and size together
import { useRef } from "react";
import { useBoundingclientrect } from "rooks";
function PositionedCard() {
const cardRef = useRef(null);
const rect = useBoundingclientrect(cardRef);
return (
<div>
<div
ref={cardRef}
style={{
position: "absolute",
top: 24,
left: 32,
width: 260,
padding: 16,
border: "1px solid #d1d5db",
}}
>
Measure my size and position.
</div>
<p>Width: {rect?.width ?? 0}px</p>
<p>Height: {rect?.height ?? 0}px</p>
<p>Top: {rect?.top ?? 0}px</p>
<p>Left: {rect?.left ?? 0}px</p>
</div>
);
}Arguments
| Argument | Type | Description |
|---|---|---|
| ref | React ref | React ref whose boundingClientRect is to be found |
Return value
| Return value | Type | Description | Default value |
|---|---|---|---|
| value | DOMRect | DOMRect Object containing x,y, width, height, left,right,top and bottom keys | null |