Wrapping React Components Inside Custom Elements

Image for post
Image for post
Web Components

React and Web Components

Wrapping React Component inside a Custom Element

export default class CollapsiblePanel extends HTMLElement {}window.customElements.define('collapsible-panel', CollapsiblePanel);
mountPoint: HTMLSpanElement;
title: string;
connectedCallback() {
this.mountPoint = document.createElement('span');
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.appendChild(this.mountPoint);

const title = this.getAttribute('title');
ReactDOM.render(this.createCollapsed(title), this.mountPoint);
retargetEvents(shadowRoot);
}
createCollapsed(title) {
return React.createElement(CollapsibleReact, { title }, React.createElement('slot'));
}
static get observedAttributes() {
return ['title'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'title') {
ReactDOM.render(this.createCollapsed(newValue), this.mountPoint);
}
}

Re-targeting React Events

Testing The Wrapper

Image for post
Image for post
Angular app hosting a React wrapped component

Summary

Written by

Hardcore web developer, @sparXys CEO, Google Web Technologies GDE, Microsoft MVP, Pro SPA Development co-author, husband, dad and a geek.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store