Skip to content

Commit 43cb138

Browse files
committed
useModalClose: add normaliser for when passedRef is a forwarded ref
1 parent abc09e9 commit 43cb138

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

client/common/useModalClose.ts

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect, useRef, MutableRefObject } from 'react';
1+
import { useEffect, useRef, MutableRefObject, ForwardedRef } from 'react';
22
import { useKeyDownHandlers } from './useKeyDownHandlers';
33

44
/**
@@ -20,10 +20,27 @@ import { useKeyDownHandlers } from './useKeyDownHandlers';
2020
*/
2121
export function useModalClose<T extends HTMLElement = HTMLElement>(
2222
onClose: () => void,
23-
passedRef?: MutableRefObject<T | null>
23+
passedRef?: MutableRefObject<T | null> | ForwardedRef<T>
2424
): MutableRefObject<T | null> {
2525
const createdRef = useRef<T | null>(null);
26-
const modalRef = passedRef ?? createdRef;
26+
27+
// Normalize any ref to a MutableRefObject internally
28+
const modalRef: MutableRefObject<T | null> = (() => {
29+
if (!passedRef) return createdRef;
30+
if (typeof passedRef === 'function') {
31+
// For function refs, write to createdRef and call the function
32+
return {
33+
get current() {
34+
return createdRef.current;
35+
},
36+
set current(value: T | null) {
37+
createdRef.current = value;
38+
passedRef(value);
39+
}
40+
};
41+
}
42+
return passedRef;
43+
})();
2744

2845
useEffect(() => {
2946
modalRef.current?.focus();

0 commit comments

Comments
 (0)