JSFiddle - React, Tailwind, and code Playground
HTML
<div id="app">
<simple-component/>
</div>
<template id="tmpl">
<label></label>
<input/>
<style>
input {
padding: 8px;
border-radius: 8px;
border: 1px solid #000;
font-size: 1.2em;
margin-bottom: 16px;
}
label {
display: block;
margin-bottom: 8px;
}
</style>
</template>
CSS
#app {
min-height: 200px;
padding: 20px 4px;
margin: 10px 4px;
}
JavaScript
class SimpleComponent extends HTMLElement {
now; label; input; text;
constructor() {
// All code here only runs once
super()
const tmpl = document.getElementById("tmpl")
console.log("Rendering...")
this.now = new Date()
this.label = tmpl.content.querySelector("label")
this.label.innerText = `Your name is: (Start typing...) (${this.now.toISOString()})`
this.input = tmpl.content.querySelector("input")
this.input.addEventListener("keyup", this.handleKeyUp.bind(this))
const root = this.attachShadow({ mode: "open" })
root.appendChild(tmpl.content)
}
handleKeyUp(evt) {
// Only this code is executed on state change.
const name = evt.target.value
console.log(name)
this.text = (name === "")
? "Your name is (Start typing...)"
: "Your name is: " + name
this.text += ` (${this.now.toISOString()})`
this.label.innerText = this.text
}
}
customElements.define("simple-component", SimpleComponent);