File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ "use client"
2
+
3
+ import { type RefObject , useEffect , useState } from "react"
4
+
5
+ import { useEventListener } from "./useEventListener"
6
+
7
+ export const useRefWidth = (
8
+ ref : RefObject < HTMLElement > ,
9
+ padding : number = 0
10
+ ) : number => {
11
+ const [ width , setWidth ] = useState ( 0 )
12
+
13
+ const updateWidth = ( ) => {
14
+ if ( ref . current ) {
15
+ const rect = ref . current . getBoundingClientRect ( )
16
+ setWidth ( Math . max ( 0 , rect . width - padding ) )
17
+ }
18
+ }
19
+
20
+ // Use the internal useEventListener for window resize
21
+ useEventListener ( "resize" , updateWidth )
22
+
23
+ useEffect ( ( ) => {
24
+ // Initial measurement
25
+ updateWidth ( )
26
+
27
+ // Create ResizeObserver for more accurate monitoring
28
+ const resizeObserver = new ResizeObserver ( updateWidth )
29
+ if ( ref . current ) {
30
+ resizeObserver . observe ( ref . current )
31
+ }
32
+
33
+ return ( ) => {
34
+ resizeObserver . disconnect ( )
35
+ }
36
+ } , [ ref , padding ] )
37
+
38
+ return width
39
+ }
You can’t perform that action at this time.
0 commit comments