Last active
December 15, 2021 02:24
-
-
Save wangpin34/35f633070a4fb97b3ea2b1d7449f44de to your computer and use it in GitHub Desktop.
Render component in shadow tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useCallback } from 'react' | |
import { render } from 'react-dom' | |
function Others() { | |
return <div>other will be rendered inside shadow tree</div> | |
} | |
class RendereComponent extends HTMLElement { | |
connectedCallback() { | |
const shadowRoot = this.attachShadow({ mode: 'open' }) | |
const mountPoint = document.createElement('div') | |
// first we need to store a reference to an element INSIDE of the shadow root | |
shadowRoot.appendChild(mountPoint) | |
// finally we need to wrap our application in a StylesProvider | |
render(<Others />, mountPoint) | |
} | |
} | |
customElements.define('wc-renderer', RendereComponent) | |
function App() { | |
const ref = useCallback((node: HTMLDivElement | null) => { | |
if (node !== null) { | |
render(<wc-renderer></wc-renderer>, node?.current) | |
} | |
}, []) | |
return <div ref={ref} /> | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { render } from 'react-dom' | |
import { useCallback } from 'react' | |
interface ShadowProps { | |
children: any | |
[p: string]: any | |
} | |
function Shadow(props: ShadowProps) { | |
const ref = useCallback((node: HTMLDivElement | null) => { | |
if (node !== null) { | |
const shadow = node.attachShadow({ mode: 'open' }) | |
const style = document.createElement('style') | |
const styleContent = ` | |
:host { | |
all: initial; | |
} | |
` | |
style.type = 'text/css' | |
style.appendChild(document.createTextNode(styleContent)) | |
render(props.children, shadow) | |
shadow.appendChild(style) | |
} | |
}, []) | |
return <div ref={ref} /> | |
} | |
function Others() { | |
return <div>other will be rendered inside shadow tree</div> | |
} | |
function App() { | |
return ( | |
<Shadow> | |
<Others/> | |
</Shadow> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment