Created
April 6, 2020 20:37
-
-
Save jmfrancois/90fecb86695f38e0e234f3ac1ad050c7 to your computer and use it in GitHub Desktop.
how to render webcomponent in react
This file contains hidden or 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
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