prime-react-webcomponent/index.js

61 lines
1.3 KiB
JavaScript
Raw Normal View History

2022-07-15 06:20:05 +00:00
import React, { useState } from 'react';
import { Button } from 'primereact/button';
import ReactDOM from 'react-dom/client';
import logo from './logo.svg';
2022-07-15 15:04:59 +00:00
const WcTestApp = (props) => {
2022-07-15 06:20:05 +00:00
const [ctr,incr] = useState(0)
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
2022-07-15 15:04:59 +00:00
<p>Hello! {props.name}.</p>
2022-07-15 06:20:05 +00:00
<Button label={`clicked ${ctr} times`} icon="pi pi-check" onClick={()=>{incr(ctr+1)}}/>
</header>
</div>
);
}
2022-07-15 15:04:59 +00:00
WcTestApp.defaultProps = {
name: 'World'
};
// a wrapper class for react component
2022-07-15 06:20:05 +00:00
class WcTest extends HTMLElement {
2022-07-15 15:04:59 +00:00
root;
2022-07-18 03:10:42 +00:00
constructor(){
super()
2022-07-15 15:04:59 +00:00
let mountPoint = this;
2022-07-15 06:20:05 +00:00
// ShadowRoot (global styles will not apply, but safer with a complete isolation layer)
2022-07-15 15:04:59 +00:00
// mountPoint = this.attachShadow({ mode: 'open' });
this.root = ReactDOM.createRoot(mountPoint);
this.render()
}
2022-07-15 06:20:05 +00:00
2022-07-18 03:10:42 +00:00
// declare attributes we want to keep track of
static get observedAttributes() {
return ['name', 'onclick'];
}
// connectedCallback() {
// }
2022-07-15 06:20:05 +00:00
2022-07-18 03:10:42 +00:00
render(){
2022-07-15 15:04:59 +00:00
const name = this.hasAttribute('name')
? this.getAttribute('name')
: undefined;
this.root.render(<WcTestApp name={name} />);
2022-07-15 06:20:05 +00:00
}
2022-07-15 15:04:59 +00:00
attributeChangedCallback(){
this.render()
}
2022-07-15 06:20:05 +00:00
}
customElements.define('wc-test', WcTest);