-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathuseIsOverflowing.ts
More file actions
33 lines (27 loc) · 1020 Bytes
/
useIsOverflowing.ts
File metadata and controls
33 lines (27 loc) · 1020 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { useEffect, useState } from 'react'
// this hook returns whether the element is overflowing by using a resize
// observer on the element
export const useIsOverflowing = (ref: React.RefObject<HTMLDivElement>) => {
// keep track of whether the element is overflowing
const [isOverflowing, setIsOverflowing] = useState(false)
useEffect(() => {
// if the ref is not available, return
if (!ref.current) return
// create a resize observer to watch for changes in the element's size
const resizeObserver = new ResizeObserver((entries) => {
const entry = entries?.[0]
if (entry) {
// if the element is overflowing, set the state
setIsOverflowing(entry.target.scrollWidth > entry.target.clientWidth)
}
})
// observe the element
resizeObserver.observe(ref.current)
return () => {
// disconnect the resize observer
resizeObserver.disconnect()
}
}, [ref])
// return whether the element is overflowing
return isOverflowing
}