Skip to content

Commit d82edab

Browse files
committed
useDynamicHeight hook added
1 parent a4c2011 commit d82edab

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

hooks/useDynamicHeight.tsx

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import * as React from "react"
2+
3+
interface HEIGHT_HOOK {
4+
ref: React.RefObject<HTMLDivElement | null>
5+
height: number
6+
}
7+
8+
const useDynamicHeight = (): HEIGHT_HOOK => {
9+
const ref = React.useRef<HTMLDivElement>(null)
10+
const [height, setHeight] = React.useState(0)
11+
12+
React.useEffect(() => {
13+
const observer = new ResizeObserver((entries) => {
14+
for (const entry of entries) {
15+
const rect = entry.target.getBoundingClientRect()
16+
setHeight(rect.height)
17+
}
18+
})
19+
20+
if (ref.current !== null) {
21+
observer.observe(ref.current)
22+
}
23+
24+
return () => {
25+
observer.disconnect()
26+
}
27+
}, [])
28+
29+
return { ref, height }
30+
}
31+
32+
export default useDynamicHeight

0 commit comments

Comments
 (0)