Skip to content

Commit b7445bc

Browse files
feat(@clayui/shared): Extract to a function so the div is created with all its attributes
1 parent 132ab1e commit b7445bc

File tree

2 files changed

+51
-22
lines changed

2 files changed

+51
-22
lines changed

packages/clay-shared/src/Portal.tsx

Lines changed: 50 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -12,22 +12,58 @@ const ClayPortalContext = React.createContext<React.RefObject<Element | null> |
1212

1313
ClayPortalContext.displayName = 'ClayPortalContext';
1414

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+
}) => {
2861
const parentPortalRef = React.useContext(ClayPortalContext);
62+
2963
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
3167
);
3268

3369
React.useEffect(() => {
@@ -42,13 +78,6 @@ export const ClayPortal: React.FunctionComponent<
4278
: closestParent;
4379

4480
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-
5281
elToMountTo.appendChild(portalRef.current);
5382
}
5483

packages/clay-shared/src/__tests__/Portal.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,4 +153,4 @@ describe('Portal', () => {
153153

154154
expect(document.body).toMatchSnapshot();
155155
});
156-
});
156+
});

0 commit comments

Comments
 (0)