From dbf30e3d73259b6d219bb771e30bbc00c56e0cc4 Mon Sep 17 00:00:00 2001 From: Ademola Adegbuyi Date: Sat, 12 Apr 2025 22:12:24 +0100 Subject: [PATCH] fix(refs): add support for react19 --- src/index.tsx | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/src/index.tsx b/src/index.tsx index ba327d0..77c3010 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,4 +1,5 @@ import React, { + Ref, useRef, useEffect, RefCallback, @@ -32,6 +33,20 @@ const eventTypeMapping = { touchend: 'onTouchEnd' }; +function useForkRef( + ...refs: Array | undefined> +): RefCallback { + return (node: T) => { + refs.forEach((ref) => { + if (typeof ref === 'function') { + ref(node); + } else if (ref != null && typeof ref === 'object') { + (ref as MutableRefObject).current = node; + } + }); + }; +} + const ClickAwayListener: FunctionComponent = ({ children, onClickAway, @@ -69,19 +84,9 @@ const ClickAwayListener: FunctionComponent = ({ } }; - const handleChildRef = (childRef: HTMLElement) => { - node.current = childRef; - - let { ref } = children as typeof children & { - ref: RefCallback | MutableRefObject; - }; - - 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; @@ -117,7 +122,7 @@ const ClickAwayListener: FunctionComponent = ({ return React.Children.only( cloneElement(children as ReactElement, { - ref: handleChildRef, + ref: combinedRef, [mappedFocusEvent]: handleBubbledEvents(mappedFocusEvent), [mappedMouseEvent]: handleBubbledEvents(mappedMouseEvent), [mappedTouchEvent]: handleBubbledEvents(mappedTouchEvent)