Skip to content

Commit dbf30e3

Browse files
committed
fix(refs): add support for react19
1 parent de2748b commit dbf30e3

File tree

1 file changed

+19
-14
lines changed

1 file changed

+19
-14
lines changed

src/index.tsx

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import React, {
2+
Ref,
23
useRef,
34
useEffect,
45
RefCallback,
@@ -32,6 +33,20 @@ const eventTypeMapping = {
3233
touchend: 'onTouchEnd'
3334
};
3435

36+
function useForkRef<T = any>(
37+
...refs: Array<Ref<T> | undefined>
38+
): RefCallback<T> {
39+
return (node: T) => {
40+
refs.forEach((ref) => {
41+
if (typeof ref === 'function') {
42+
ref(node);
43+
} else if (ref != null && typeof ref === 'object') {
44+
(ref as MutableRefObject<T | null>).current = node;
45+
}
46+
});
47+
};
48+
}
49+
3550
const ClickAwayListener: FunctionComponent<Props> = ({
3651
children,
3752
onClickAway,
@@ -69,19 +84,9 @@ const ClickAwayListener: FunctionComponent<Props> = ({
6984
}
7085
};
7186

72-
const handleChildRef = (childRef: HTMLElement) => {
73-
node.current = childRef;
74-
75-
let { ref } = children as typeof children & {
76-
ref: RefCallback<HTMLElement> | MutableRefObject<HTMLElement>;
77-
};
78-
79-
if (typeof ref === 'function') {
80-
ref(childRef);
81-
} else if (ref) {
82-
ref.current = childRef;
83-
}
84-
};
87+
const combinedRef = useForkRef((ref) => {
88+
node.current = ref;
89+
}, (children as any).ref);
8590

8691
useEffect(() => {
8792
const nodeDocument = node.current?.ownerDocument ?? document;
@@ -117,7 +122,7 @@ const ClickAwayListener: FunctionComponent<Props> = ({
117122

118123
return React.Children.only(
119124
cloneElement(children as ReactElement<any>, {
120-
ref: handleChildRef,
125+
ref: combinedRef,
121126
[mappedFocusEvent]: handleBubbledEvents(mappedFocusEvent),
122127
[mappedMouseEvent]: handleBubbledEvents(mappedMouseEvent),
123128
[mappedTouchEvent]: handleBubbledEvents(mappedTouchEvent)

0 commit comments

Comments
 (0)