Use in React
First off, let's create a new React app, so we can experiment:
npx create-react-app webcomp --template clean-cra
Now modify index.js to reflect the new createRoot method:
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
const container = document.getElementById('root')
const root = ReactDOM.createRoot(container)
root.render(<App />)
Web Component
Now we can create this (very, very simple) Web Component:
File: cool-message.js
class CoolMessageComponent extends HTMLElement {
constructor() {
super()
this.msg = ''
}
// component attributes
static get observedAttributes() {
return ['msg']
}
/// Show the output
print() {
this.innerHTML = `<strong>${ this.msg }</strong>`
}
// attribute change
attributeChangedCallback(property, oldValue, newValue) {
if (oldValue === newValue) return
this.msg = newValue
this.print()
}
// connect component
connectedCallback() {
this.print()
}
}
customElements.define("cool-message", CoolMessageComponent)
And call it inside our React app:
File: App.js
import React, { useState } from 'react';
import './cool-message.js'
const App = () => {
const [msg, setMsg] = useState('0');
const [count, setCount] = useState(0)
const updateComponent = () => {
setCount(count + 1)
setMsg(`Clicked ${count} times`)
}
return (
<divs>
<cool-message msg={msg} />
<button onClick={() => updateComponent() }>set message</button>
</divs>
)
}
export default App