1
+ import { useInterval } from "@react-hooks-library/core"
1
2
import { useCallback , useEffect , useRef , useState } from 'react'
2
3
3
4
/**
@@ -57,4 +58,43 @@ export function useKeepBottom<E extends HTMLElement>(enabled: boolean, calculate
57
58
} , [ ] )
58
59
59
60
return { ref : refCallback , element : ref , keepBottom }
61
+ }
62
+
63
+
64
+
65
+
66
+ /**
67
+ * Custom hook that queries the DOM for an element matching the given selector.
68
+ * Optionally, it can remount and re-query the DOM at a specified interval.
69
+ *
70
+ * @param {string } selector - The CSS selector to query the DOM.
71
+ * @param {boolean } [remount=false] - If true, the hook will re-query the DOM at the specified interval.
72
+ * @returns {Element | null } - The DOM element matching the selector, or null if no element is found.
73
+ *
74
+ * @example
75
+ * // Usage in a React component
76
+ * const MyComponent = () => {
77
+ * const element = useQuerySelector('#my-element', true);
78
+ *
79
+ * useEffect(() => {
80
+ * if (element) {
81
+ * console.log('Element found:', element);
82
+ * }
83
+ * }, [element]);
84
+ *
85
+ * return <div>Check the console for the element.</div>;
86
+ * };
87
+ */
88
+ export function useQuerySelector < E extends Element > ( selector : string , remount : boolean = false ) : E | null {
89
+
90
+ const [ element , setElement ] = useState < Element | null > ( document . querySelector ( selector ) )
91
+
92
+ useInterval ( ( ) => {
93
+ const el = document . querySelector ( selector )
94
+ if ( el ) {
95
+ setElement ( el )
96
+ }
97
+ } , 500 , { paused : ! remount && ! ! element , immediate : true } )
98
+
99
+ return element as E
60
100
}
0 commit comments