-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathrenderReactInWebComponent.ts
158 lines (134 loc) · 5.68 KB
/
renderReactInWebComponent.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
/*!
* Copyright (c) 2024-present, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/
import { type ReactNode } from "react";
import type { Root } from "react-dom/client";
/**
* Creates elements for a Shadow DOM that Odyssey will render into.
* The Emotion root is for `<style>` tags and the app root is for an app to render into.
* These are bare elements that
*/
export const createReactRootElements = () => {
const appRootElement = document.createElement("div");
const stylesRootElement = document.createElement("div");
// This `div` may cause layout issues unless it inherits the parent's height.
appRootElement.style.setProperty("height", "inherit");
appRootElement.setAttribute("id", "app-root");
stylesRootElement.setAttribute("id", "style-root");
stylesRootElement.setAttribute("nonce", window.cspNonce);
return {
/**
* The element your React root component renders into.
* React has to render or portal somewhere, and this element can be used for that root element.
*
* In the case of a web component, there is no defined root element, so you have to define it yourself.
*/
appRootElement,
/**
* In React apps, your styles typically go in `document.head`, but you may want to render them somewhere else.
*
* Specifically when rendering in a web component, there is no `<head>`, so you have to create a spot for styles to render.
*/
stylesRootElement,
};
};
export type ReactRootElements = ReturnType<typeof createReactRootElements>;
export const reactWebComponentElementName = "odyssey-react-web-component";
export type GetReactComponentInWebComponent = (
reactRootElements: ReactRootElements,
) => ReactNode;
export class ReactInWebComponentElement extends HTMLElement {
getReactComponent: GetReactComponentInWebComponent;
reactRootElements: ReactRootElements;
reactRootPromise: Promise<Root>;
constructor(getReactComponent: GetReactComponentInWebComponent) {
super();
this.getReactComponent = getReactComponent;
this.reactRootElements = createReactRootElements();
const styleElement = document.createElement("style");
const shadowRoot = this.attachShadow({ mode: "open" });
styleElement.innerHTML = `
:host {
all: initial;
contain: content;
}
`;
styleElement.setAttribute("nonce", window.cspNonce);
this.reactRootElements.stylesRootElement.appendChild(styleElement);
shadowRoot.appendChild(this.reactRootElements.stylesRootElement);
shadowRoot.appendChild(this.reactRootElements.appRootElement);
// If we want to support React v17 in the future, we can use a try-catch on the import to grab the old `ReactDOM.render` function if `react-dom/client` errors. --Kevin Ghadyani
this.reactRootPromise = import("react-dom/client").then(({ createRoot }) =>
createRoot(this.reactRootElements.appRootElement),
);
}
connectedCallback() {
this.reactRootPromise.then((reactRoot) =>
reactRoot.render(this.getReactComponent(this.reactRootElements)),
);
}
disconnectedCallback() {
this.reactRootPromise.then((reactRoot) => reactRoot.unmount());
}
}
if (!customElements.get(reactWebComponentElementName)) {
customElements.define(
reactWebComponentElementName,
ReactInWebComponentElement,
);
}
export type RenderReactInWebComponentProps = {
/**
* This is a callback function for rendering your React component or app in the Web Component.
* It gives you access to the Shadow DOM elements if you need them for Odyssey, Emotion, or MUI.
*
* You will need to add `<slot>` elements if you want to pass child elements or components or React apps.
* You can have multiple slots in your app if you add a `name` attribute to your `<slot>` elements.
*/
getReactComponent: GetReactComponentInWebComponent;
/**
* One or more HTML elements that are going to render as `children` of the web component.
* If your React component doesn't take children, this is unnecessary.
*
* Typically, a React app root element is passed, but it can include an array of other elements if there are multiple slots for children.
*
* You will need to have rendered `<slot>` elements in your React component or `children` won't show up.
*/
webComponentChildren?: HTMLElement | HTMLElement[];
/**
* You React app renders in the web component, but the web component needs to be rendered in the document.
*
* This is the element the web component is rendered into.
*/
webComponentRootElement: HTMLElement;
};
/**
* Lets you render React apps or components in a Web Component.
*
* This is useful when global styles are causing conflicts with your React components.
*/
export const renderReactInWebComponent = ({
getReactComponent,
webComponentChildren,
webComponentRootElement,
}: RenderReactInWebComponentProps) => {
const reactElement = new ReactInWebComponentElement(getReactComponent);
if (webComponentChildren) {
(Array.isArray(webComponentChildren)
? webComponentChildren
: [webComponentChildren]
).forEach((webComponentChild) => {
reactElement.appendChild(webComponentChild);
});
}
webComponentRootElement.appendChild(reactElement);
return reactElement;
};