vanilla-state-mgr-01
by Nic Fontaine
HTML
<input id="input-name" placeholder="Type a new App name">
<button id="btn-change">Submit</button>
<hr>
<div id="root"></div>
<p>Sed interdum id turpis at placerat. Quisque a enim et odio luctus tincidunt. Maecenas vel massa ligula. Quisque diam libero, dictum vel consequat vitae, pretium nec urna.</p>
JavaScript
class App {
constructor(name) {
this.state = {
name: name,
err: ""
}
this.render()
this.inputName = document.getElementById("input-name")
this.btnChange = document.getElementById("btn-change")
this.outputStatus = document.getElementById("output-status")
let input = this.inputName
this.btnChange.addEventListener("click", (e) => {
e.preventDefault()
if (!input.value.length || input.value === this.state.name) {
this.state = { ...this.state, err: "ERROR: Name is the same or empty"}
} else {
this.state = {
...this.state,
name: input.value,
err: ""
}
input.value = ""
}
this.render()
})
}
render() {
const { name, err } = this.state
document.getElementById("root").innerHTML = `
<h1>${name}</h1>
<div id="output-status" style="color:${err ? `red` : `gray`}">(${err ? err : "Up-to-date"})</div>
`
}
}
new App("Test Name")