/defineReactComponent.ts Secret
Created
June 20, 2019 10:09
The define react component function
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
export const defineReactComponent = (Component, name) => { | |
const observed = getObserved(Component); | |
class Wrapper extends HTMLElement { | |
static get observedAttributes() { | |
return observed; | |
} | |
mountPoint: HTMLSpanElement; | |
createComponent(props) { | |
return React.createElement(Component, props, React.createElement('slot')); | |
} | |
generateAllProps(cmp) { | |
const propsDef = {}; | |
Object.keys(cmp.propTypes).forEach((prop) => { | |
propsDef[prop] = this.getAttribute(prop); | |
}); | |
return propsDef; | |
} | |
connectedCallback() { | |
this.mountPoint = document.createElement('span'); | |
const shadowRoot = this.attachShadow({ mode: 'open' }); | |
shadowRoot.appendChild(this.mountPoint); | |
ReactDOM.render(this.createComponent(this.generateAllProps(Component)), this.mountPoint); | |
retargetEvents(shadowRoot); | |
} | |
attributeChangedCallback(attrName) { | |
if (Wrapper.observedAttributes.indexOf(attrName) >= 0) { | |
ReactDOM.render(this.createComponent(this.generateAllProps(Component)), this.mountPoint); | |
} | |
} | |
} | |
window.customElements.define(name, Wrapper); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment