Skip to content
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