-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseWidth.ts
More file actions
35 lines (28 loc) · 1.01 KB
/
useWidth.ts
File metadata and controls
35 lines (28 loc) · 1.01 KB
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
34
35
import { useLayoutEffect, useRef, useState } from 'react'
const defaultWidth = 320
export function useWidth<T extends HTMLElement = HTMLElement>() {
const [width, setWidth] = useState(defaultWidth)
const elementRef = useRef<T>(null)
useLayoutEffect(() => {
function updateWidth() {
if (elementRef.current) {
// Get the parent container width instead of the span itself
const container = elementRef.current.parentElement
const containerWidth = container ? container.clientWidth : elementRef.current.clientWidth
setWidth(containerWidth || defaultWidth)
}
}
updateWidth()
// Only use ResizeObserver if it's available
if (typeof ResizeObserver !== 'undefined') {
const resizeObserver = new ResizeObserver(updateWidth)
if (elementRef.current?.parentElement) {
resizeObserver.observe(elementRef.current.parentElement)
}
return () => {
resizeObserver.disconnect()
}
}
}, [])
return { elementRef, width }
}