I created a simple React component.
const ReactComponent = () => {
const [name, setName] = useState("something");
return <div>Hello {name}</div>
}
export default ReactComponent;
And I used react-to-webcomponent library to convert it to a plain HTML tag which gives me tags which I can use in any page. But I want to use it inside a standalone HTML page with vanilla js.
index.html
<script async defer src='index.js'></script>
<body>
<div id='main>Hello World</div>
</body>
index.js
import {initComponent} from '/ReactComponentWC.js'
const main = document.getElementById("main");
initComponent(main)
In ReactComponentWC.js
const initComponent = (containerElement) => {
const reactElement = r2wc(ReactComponent, React, ReactDOM)
customElements.define("react-component", reactElement)
const myComp = document.createElement('div')
myComp.innerHTML = `<react-component />`
containerElement.appendChild(myComp)
}
export { initComponent }
When I load the index.html on Live Server, I get this error
‘Uncaught TypeError: Failed to resolve module specifier “react”. Relative references must start with either “/”, “./”, or “../”.’
Then I tried to bundle the ReactComponentWC.js file using webpack. Now when I imported from the bundled /dist/ReactComponent.js file, it showed “no export named initComponent found”
. This import works fine in any nextjs page in my app. The error occurs only in this standalone HTML page.
Any suggestions on how I can export my react component so that it can be used by any JS frontend framework or even vanilla js apps? Thanks in advance!