Created
September 29, 2021 23:18
-
-
Save petermikitsh/3e8a69e55ef4928838b35a5fe410d5d6 to your computer and use it in GitHub Desktop.
react-shadow-dom.html
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>React + Shadow DOM</title> | |
</head> | |
<body style="margin: 0"> | |
<global-navigation> | |
<div slot="breadcrumbContent" style="color: red">Breadcrumbs</div> | |
<div slot="pageContent" style="color: blue">Page Content</div> | |
</global-navigation> | |
<script | |
crossorigin | |
src="https://unpkg.com/react@17/umd/react.development.js" | |
></script> | |
<script | |
crossorigin | |
src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" | |
></script> | |
<script type="text/javascript"> | |
const MyElement = () => { | |
const [count, setCount] = React.useState(1); | |
React.useEffect(() => { | |
const timer = setInterval(() => { | |
setCount((prevCount) => prevCount + 1); | |
}, 1000); | |
return () => { | |
clearInterval(timer); | |
}; | |
}, []); | |
return React.createElement("div", {}, [ | |
"A", | |
React.createElement("slot", { | |
key: "breadcrumb", | |
name: "breadcrumbContent", | |
}), | |
"B", | |
React.createElement("slot", { | |
key: "page", | |
name: "pageContent", | |
}), | |
"C", | |
React.createElement("div", { key: "livecount" }, count), | |
]); | |
}; | |
window.customElements.define( | |
"global-navigation", | |
class MyOuterStuff extends HTMLElement { | |
connectedCallback() { | |
const shadow = this.attachShadow({ mode: "open" }); | |
shadow.innerHTML = ` | |
<style> | |
::slotted([slot="pageContent"]) { | |
padding: 16px; | |
} | |
</style> | |
`; | |
const mount = document.createElement("div"); | |
shadow.appendChild(mount); | |
ReactDOM.render(React.createElement(MyElement), mount); | |
} | |
} | |
); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment