Skip to content

Instantly share code, notes, and snippets.

@conor909
Last active November 11, 2019 07:00
Show Gist options
  • Save conor909/8466594f678d82d7469b2ff70af2e0cb to your computer and use it in GitHub Desktop.
Save conor909/8466594f678d82d7469b2ff70af2e0cb to your computer and use it in GitHub Desktop.
React app inside a web component
import React from 'react'
import { render as renderReact } from 'react-dom'
import retargetEvents from 'react-shadow-dom-retarget-events'
import App from './App'
(function() {
window.addEventListener('WebComponentsReady', () => {
class MyApp extends HTMLElement {
constructor() {
super()
this.shadow = this.attachShadow({ mode: 'closed' })
}
static get observedAttributes() {
return [ 'name' ]
}
connectedCallback() {
const template = `
<style>
@import 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css';
</style>
<div id="root"></div>
`;
this.shadow.innerHTML = template;
this.render();
retargetEvents(this.shadow)
}
render() {
renderReact(
<App name={ this.getAttribute('name') } />, this.shadow.getElementById('root')
)
}
}
window.customElements.define('custom-component', MyApp)
})
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment