Skip to content

Instantly share code, notes, and snippets.

@jmfrancois
Created April 6, 2020 20:37
Show Gist options
  • Save jmfrancois/90fecb86695f38e0e234f3ac1ad050c7 to your computer and use it in GitHub Desktop.
Save jmfrancois/90fecb86695f38e0e234f3ac1ad050c7 to your computer and use it in GitHub Desktop.
how to render webcomponent in react
import React from 'react';
export default function WebComponent({ component, ...props }) {
const [myEl, setState] = React.useState(document.createElement(component));
const el = React.useRef(null);
React.useEffect(() => {
if (myEl.tagName.toLowerCase() !== component.toLowerCase() ) {
setState(document.createElement(component));
} else {
Object.keys(props).forEach(key => {
if (typeof props[key] === 'string') {
myEl.setAttribute(key, props[key]);
} else {
myEl[key] = props[key];
}
});
}
if (el) {
el.appendChild(myEl);
}
});
return <div ref={(ref) => {
el = ref;
el.appendChild(myEl);
}}></div>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment