diff --git a/packages/clay-shared/src/Portal.tsx b/packages/clay-shared/src/Portal.tsx index c7ff8e1fb7..770d8a4c06 100644 --- a/packages/clay-shared/src/Portal.tsx +++ b/packages/clay-shared/src/Portal.tsx @@ -12,22 +12,58 @@ const ClayPortalContext = React.createContext | ClayPortalContext.displayName = 'ClayPortalContext'; -export const ClayPortal: React.FunctionComponent< - React.HTMLAttributes & { - /** - * Ref of element to render portal into. - */ - containerRef?: React.RefObject; - - /** - * Ref of element to render nested portals into. - */ - subPortalRef?: React.RefObject; - } -> = ({children, containerRef, subPortalRef, ...otherProps}) => { +const createElement = ( + nodeName: string, + attributes: Record +) => { + const element = document.createElement(nodeName); + + Object.keys(attributes).forEach((key) => { + element.setAttribute( + key === 'className' ? 'class' : key, + attributes[key] + ); + }); + + return element; +}; + +interface IProps { + children: React.ReactElement | Array; + + /** + * Class to add to the root element + */ + className?: string; + + /** + * Ref of element to render portal into. + */ + containerRef?: React.RefObject; + + /** + * Id fof the root element + */ + id?: string; + + /** + * Ref of element to render nested portals into. + */ + subPortalRef?: React.RefObject; +} + +export const ClayPortal: React.FunctionComponent = ({ + children, + containerRef, + subPortalRef, + ...otherProps +}) => { const parentPortalRef = React.useContext(ClayPortalContext); + const portalRef = React.useRef( - typeof document !== 'undefined' ? document.createElement('div') : null + typeof document !== 'undefined' + ? createElement('div', otherProps as Record) + : null ); React.useEffect(() => { @@ -42,13 +78,6 @@ export const ClayPortal: React.FunctionComponent< : closestParent; if (elToMountTo && portalRef.current) { - if (otherProps?.className) { - portalRef.current.classList.add(otherProps.className); - } - if (otherProps?.id) { - portalRef.current.id = otherProps.id; - } - elToMountTo.appendChild(portalRef.current); } diff --git a/packages/clay-shared/src/__tests__/Portal.tsx b/packages/clay-shared/src/__tests__/Portal.tsx index 61c498c6ec..cdbbb86f0e 100644 --- a/packages/clay-shared/src/__tests__/Portal.tsx +++ b/packages/clay-shared/src/__tests__/Portal.tsx @@ -153,4 +153,4 @@ describe('Portal', () => { expect(document.body).toMatchSnapshot(); }); -}); \ No newline at end of file +});