Skip to content

Instantly share code, notes, and snippets.

@gilf
Created June 20, 2019 10:09
The define react component function
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