Skip to content

Commit 7f4367c

Browse files
committed
Allow BodyPortals to accept ref parameter
1 parent 78ef540 commit 7f4367c

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

src/components/BodyPortal.tsx

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,18 +22,25 @@ const getInsertBeforeTarget = (bodyPortalSlots: string[], slot?: string) => {
2222
}
2323

2424
export const BodyPortal = ({
25-
children, className, role, slot, tagName
26-
}: React.PropsWithChildren<{className?: string; role?: string; slot?: string; tagName?: string}>) => {
25+
children, className, ref, role, slot, tagName
26+
}: React.PropsWithChildren<{
27+
className?: string;
28+
ref?: React.MutableRefObject<HTMLElement | null>;
29+
role?: string;
30+
slot?: string;
31+
tagName?: string
32+
}>) => {
2733
const tag = tagName?.toUpperCase() ?? 'DIV';
28-
const ref = React.useRef<HTMLElement>(document.createElement(tag));
29-
if (ref.current.tagName !== tag) {
30-
ref.current = document.createElement(tag);
34+
const internalRef = React.useRef<HTMLElement>(document.createElement(tag));
35+
if (internalRef.current.tagName !== tag) {
36+
internalRef.current = document.createElement(tag);
3137
}
38+
if (ref) { ref.current = internalRef.current; }
3239

3340
const bodyPortalOrderedRefs = React.useContext(BodyPortalSlotsContext);
3441

3542
React.useLayoutEffect(() => {
36-
const element = ref.current;
43+
const element = internalRef.current;
3744

3845
if (className) { element.classList.add(...className.split(' ')); }
3946

@@ -56,5 +63,5 @@ export const BodyPortal = ({
5663
};
5764
}, [bodyPortalOrderedRefs, className, role, slot, tag]);
5865

59-
return createPortal(children, ref.current);
66+
return createPortal(children, internalRef.current);
6067
};

0 commit comments

Comments
 (0)