Good webpage
Here's legacy React's like_button.js, without JSX, from their old documentation:
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
const domContainer = document.querySelector('#like_button_container');
const root = ReactDOM.createRoot(domContainer);
root.render(e(LikeButton));
Here's the equivalent using the Web Components specification[1]: // https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements
// Create a class for the element
class LikeButton extends HTMLElement {
static get observedAttributes() { return ['liked']; }
constructor() {
// Always call super first in constructor
super();
this.liked = false;
// Create a shadow root
/* const shadow = */ this.attachShadow({mode: 'open'});
}
get liked() { return this.hasAttribute('liked'); }
set liked(state) { this.toggleAttribute('liked', Boolean(state)); }
attributeChangedCallback(name, oldValue, newValue) {
this.render();
}
connectedCallback() {
this.render();
}
render() {
const shadow = this.shadowRoot;
if (this.liked) {
shadow.innerHTML = 'You liked this.'
return;
}
shadow.innerHTML = `<button onclick="this.parentNode.host.liked = true;">
Like
</button>`;
}
}
// Define the new element
customElements.define('like-button', LikeButton);
The React API is slightly nicer to use, especially with JSX.