|
1
|
import { |
|
2
|
MutableRefObject, |
|
3
|
ReactNode, |
|
4
|
Ref, |
|
5
|
RefAttributes, |
|
6
|
RefCallback, |
|
7
|
forwardRef, |
|
8
|
} from "react"; |
|
9
|
|
|
10
|
export function genericForwardRef<T, P = {}>( |
|
11
|
render: (props: P, ref: Ref<T>) => ReactNode |
|
12
|
): (props: P & RefAttributes<T>) => ReactNode { |
|
13
|
return forwardRef(render) as any; |
|
14
|
} |
|
15
|
|
|
16
|
// Utility function to set multiple refs |
|
17
|
function setRef<T>(ref: Ref<T> | undefined, value: T) { |
|
18
|
if (typeof ref === "function") { |
|
19
|
ref(value); |
|
20
|
} else if (ref && "current" in ref) { |
|
21
|
(ref as MutableRefObject<T>).current = value; |
|
22
|
} |
|
23
|
} |
|
24
|
|
|
25
|
// Combining multiple refs into one |
|
26
|
export const useCombinedRefs = <T,>( |
|
27
|
...refs: (Ref<T> | undefined)[] |
|
28
|
): RefCallback<T> => { |
|
29
|
return (value: T) => { |
|
30
|
refs.forEach((ref) => setRef(ref, value)); |
|
31
|
}; |
|
32
|
}; |