Skip to content

fix(refs): add support for react19 #96

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 12, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 19 additions & 14 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, {
Ref,
useRef,
useEffect,
RefCallback,
Expand Down Expand Up @@ -32,6 +33,20 @@ const eventTypeMapping = {
touchend: 'onTouchEnd'
};

function useForkRef<T = any>(
...refs: Array<Ref<T> | undefined>
): RefCallback<T> {
return (node: T) => {
refs.forEach((ref) => {
if (typeof ref === 'function') {
ref(node);
} else if (ref != null && typeof ref === 'object') {
(ref as MutableRefObject<T | null>).current = node;
}
});
};
}

const ClickAwayListener: FunctionComponent<Props> = ({
children,
onClickAway,
Expand Down Expand Up @@ -69,19 +84,9 @@ const ClickAwayListener: FunctionComponent<Props> = ({
}
};

const handleChildRef = (childRef: HTMLElement) => {
node.current = childRef;

let { ref } = children as typeof children & {
ref: RefCallback<HTMLElement> | MutableRefObject<HTMLElement>;
};

if (typeof ref === 'function') {
ref(childRef);
} else if (ref) {
ref.current = childRef;
}
};
const combinedRef = useForkRef((ref) => {
node.current = ref;
}, (children as any).ref);

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

return React.Children.only(
cloneElement(children as ReactElement<any>, {
ref: handleChildRef,
ref: combinedRef,
[mappedFocusEvent]: handleBubbledEvents(mappedFocusEvent),
[mappedMouseEvent]: handleBubbledEvents(mappedMouseEvent),
[mappedTouchEvent]: handleBubbledEvents(mappedTouchEvent)
Expand Down
Loading