-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathwc.util.tsx
More file actions
48 lines (42 loc) · 1.05 KB
/
Copy pathwc.util.tsx
File metadata and controls
48 lines (42 loc) · 1.05 KB
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
import { createRoot, Root } from "react-dom/client";
import { StyleSheetManager } from "styled-components";
import React from "react";
export function registerReactWebComponent({
name,
Component,
attributes = [],
}: {
name: string;
Component: any;
attributes?: string[];
}) {
class WebComponentClass extends HTMLElement {
private readonly shadow: ShadowRoot;
private readonly root: Root;
constructor() {
super();
this.shadow = this.attachShadow({ mode: "open" });
this.root = createRoot(this.shadow);
}
connectedCallback() {
const attrs = attributes.reduce(
(acc, key) =>
Object.assign(acc, {
[key]: this.getAttribute(key) ?? undefined,
}),
{}
);
this.root.render(
<StyleSheetManager target={this.shadow}>
<Component {...attrs} />
</StyleSheetManager>
);
}
disconnectedCallback() {
if (!this.isConnected) {
this.root.unmount();
}
}
}
customElements.define(name, WebComponentClass);
}