@@ -4,24 +4,17 @@ import useLayoutEffect from 'use-isomorphic-layout-effect';
4
4
5
5
const DEFAULT_ID = 'floating-ui-root' ;
6
6
7
- /**
8
- * Portals your floating element outside of the main app node.
9
- * @see https://floating-ui.com/docs/FloatingPortal
10
- */
11
- export const FloatingPortal = ( {
12
- children,
7
+ export const useFloatingPortalNode = ( {
13
8
id = DEFAULT_ID ,
14
- root = null ,
9
+ enabled = true ,
15
10
} : {
16
- children ?: React . ReactNode ;
17
11
id ?: string ;
18
- root ?: HTMLElement | null ;
19
- } ) : React . ReactPortal | null => {
20
- const [ mounted , setMounted ] = React . useState ( false ) ;
12
+ enabled ?: boolean ;
13
+ } = { } ) => {
21
14
const portalRef = React . useRef < HTMLElement | null > ( null ) ;
22
15
23
16
useLayoutEffect ( ( ) => {
24
- if ( root ) {
17
+ if ( ! enabled ) {
25
18
return ;
26
19
}
27
20
@@ -37,16 +30,40 @@ export const FloatingPortal = ({
37
30
if ( ! document . body . contains ( portalRef . current ) ) {
38
31
document . body . appendChild ( portalRef . current ) ;
39
32
}
33
+ } , [ id , enabled ] ) ;
34
+
35
+ return portalRef . current ;
36
+ } ;
40
37
38
+ /**
39
+ * Portals your floating element outside of the main app node.
40
+ * @see https://floating-ui.com/docs/FloatingPortal
41
+ */
42
+ export const FloatingPortal = ( {
43
+ children,
44
+ id = DEFAULT_ID ,
45
+ root = null ,
46
+ } : {
47
+ children ?: React . ReactNode ;
48
+ id ?: string ;
49
+ root ?: HTMLElement | null ;
50
+ } ) : React . ReactPortal | null => {
51
+ const [ mounted , setMounted ] = React . useState ( false ) ;
52
+ const portalNode = useFloatingPortalNode ( { id, enabled : ! root } ) ;
53
+
54
+ useLayoutEffect ( ( ) => {
55
+ if ( root ) {
56
+ return ;
57
+ }
41
58
setMounted ( true ) ;
42
- } , [ id , root ] ) ;
59
+ } , [ root ] ) ;
43
60
44
61
if ( root ) {
45
62
return createPortal ( children , root ) ;
46
63
}
47
64
48
- if ( mounted && portalRef . current ) {
49
- return createPortal ( children , portalRef . current ) ;
65
+ if ( mounted && portalNode ) {
66
+ return createPortal ( children , portalNode ) ;
50
67
}
51
68
52
69
return null ;
0 commit comments