Skip to content

Commit

Permalink
feat(@clayui/shared): Extract to a function so the div is created wit…
Browse files Browse the repository at this point in the history
…h all its attributes
  • Loading branch information
ambrinchaudhary committed May 18, 2021
1 parent 132ab1e commit b7445bc
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 22 deletions.
71 changes: 50 additions & 21 deletions packages/clay-shared/src/Portal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,58 @@ const ClayPortalContext = React.createContext<React.RefObject<Element | null> |

ClayPortalContext.displayName = 'ClayPortalContext';

export const ClayPortal: React.FunctionComponent<
React.HTMLAttributes<HTMLDivElement> & {
/**
* Ref of element to render portal into.
*/
containerRef?: React.RefObject<Element>;

/**
* Ref of element to render nested portals into.
*/
subPortalRef?: React.RefObject<Element>;
}
> = ({children, containerRef, subPortalRef, ...otherProps}) => {
const createElement = (
nodeName: string,
attributes: Record<string, string>
) => {
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<React.ReactElement>;

/**
* Class to add to the root element
*/
className?: string;

/**
* Ref of element to render portal into.
*/
containerRef?: React.RefObject<Element>;

/**
* Id fof the root element
*/
id?: string;

/**
* Ref of element to render nested portals into.
*/
subPortalRef?: React.RefObject<Element>;
}

export const ClayPortal: React.FunctionComponent<IProps> = ({
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<string, string>)
: null
);

React.useEffect(() => {
Expand All @@ -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);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/clay-shared/src/__tests__/Portal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,4 @@ describe('Portal', () => {

expect(document.body).toMatchSnapshot();
});
});
});

0 comments on commit b7445bc

Please sign in to comment.