Skip to content

Instantly share code, notes, and snippets.

@wangpin34
Last active December 15, 2021 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wangpin34/35f633070a4fb97b3ea2b1d7449f44de to your computer and use it in GitHub Desktop.
Save wangpin34/35f633070a4fb97b3ea2b1d7449f44de to your computer and use it in GitHub Desktop.
Render component in shadow tree
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} />
}

Why use shadow DOM tree?

The Problem (WIP)

Subscribe to state: Redux, Recoil

No aware of style sheets of the parent

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