@@ -12,22 +12,58 @@ const ClayPortalContext = React.createContext<React.RefObject<Element | null> |
12
12
13
13
ClayPortalContext . displayName = 'ClayPortalContext' ;
14
14
15
- export const ClayPortal : React . FunctionComponent <
16
- React . HTMLAttributes < HTMLDivElement > & {
17
- /**
18
- * Ref of element to render portal into.
19
- */
20
- containerRef ?: React . RefObject < Element > ;
21
-
22
- /**
23
- * Ref of element to render nested portals into.
24
- */
25
- subPortalRef ?: React . RefObject < Element > ;
26
- }
27
- > = ( { children, containerRef, subPortalRef, ...otherProps } ) => {
15
+ const createElement = (
16
+ nodeName : string ,
17
+ attributes : Record < string , string >
18
+ ) => {
19
+ const element = document . createElement ( nodeName ) ;
20
+
21
+ Object . keys ( attributes ) . forEach ( ( key ) => {
22
+ element . setAttribute (
23
+ key === 'className' ? 'class' : key ,
24
+ attributes [ key ]
25
+ ) ;
26
+ } ) ;
27
+
28
+ return element ;
29
+ } ;
30
+
31
+ interface IProps {
32
+ children : React . ReactElement | Array < React . ReactElement > ;
33
+
34
+ /**
35
+ * Class to add to the root element
36
+ */
37
+ className ?: string ;
38
+
39
+ /**
40
+ * Ref of element to render portal into.
41
+ */
42
+ containerRef ?: React . RefObject < Element > ;
43
+
44
+ /**
45
+ * Id fof the root element
46
+ */
47
+ id ?: string ;
48
+
49
+ /**
50
+ * Ref of element to render nested portals into.
51
+ */
52
+ subPortalRef ?: React . RefObject < Element > ;
53
+ }
54
+
55
+ export const ClayPortal : React . FunctionComponent < IProps > = ( {
56
+ children,
57
+ containerRef,
58
+ subPortalRef,
59
+ ...otherProps
60
+ } ) => {
28
61
const parentPortalRef = React . useContext ( ClayPortalContext ) ;
62
+
29
63
const portalRef = React . useRef (
30
- typeof document !== 'undefined' ? document . createElement ( 'div' ) : null
64
+ typeof document !== 'undefined'
65
+ ? createElement ( 'div' , otherProps as Record < string , string > )
66
+ : null
31
67
) ;
32
68
33
69
React . useEffect ( ( ) => {
@@ -42,13 +78,6 @@ export const ClayPortal: React.FunctionComponent<
42
78
: closestParent ;
43
79
44
80
if ( elToMountTo && portalRef . current ) {
45
- if ( otherProps ?. className ) {
46
- portalRef . current . classList . add ( otherProps . className ) ;
47
- }
48
- if ( otherProps ?. id ) {
49
- portalRef . current . id = otherProps . id ;
50
- }
51
-
52
81
elToMountTo . appendChild ( portalRef . current ) ;
53
82
}
54
83
0 commit comments