Learn about Web Components #
Web Components is using for making Javascript frameworks like React, Vue, Angular.
Here is the basic custom component
<body>
<my-button></my-button>
<script>
class MyButton extends HTMLElement {
constructor() {
super()
this.attachShadow({ mode: "open" })
this.btn = document.createElement("div")
this.btn.textContent = "My Button"
this.shadowRoot.appendChild(this.btn)
}
}
window.customElements.define("my-button", MyButton)
</script>
</body>
Style components
class MyButton extends HTMLElement {
static style = `
.btn {
display: inline-block;
color: #eeeeee;
background-color: rgb(5, 104, 5);
padding: 10px;
font-weight: 800;
}
`
constructor() {
...
this.btn.className = "btn"
this.styling()
}
styling() {
this.stylesheet = document.createElement("style")
this.stylesheet.textContent = MyButton.style
this.shadowRoot.append(this.stylesheet)
}
}
Pass the prams
You can get the string by getAttribute()
HTML:
<my-button text="Lakers"></my-button>
JS:
render() {
...
this.btn.textContent = this.getAttribute("text")
this.shadowRoot.appendChild(this.btn)
}
However, if you want to update data in the components, it needs to use observedAttributes to observe the data if it changed, and use attributeChangedCallback to do the action while data changed. Here is the final code today.
<my-button text="Lakers" id="the-button"></my-button>
<button onclick="change()">Click</button>
<script>
class MyButton extends HTMLElement {
static style = `
.btn {
display: inline-block;
color: #eeeeee;
background-color: rgb(5, 104, 5);
padding: 10px;
font-weight: 800;
}
`
static get observedAttributes() {
return ["text"]
}
constructor() {
super()
this.attachShadow({ mode: "open" })
this.render()
this.styling()
}
attributeChangedCallback(name, oldValue, newValue) {
this.btn.textContent = newValue
}
styling() {
this.stylesheet = document.createElement("style")
this.stylesheet.textContent = MyButton.style
this.shadowRoot.append(this.stylesheet)
}
render() {
this.btn = document.createElement("div")
this.btn.className = "btn"
this.btn.textContent = "My Button"
this.btn.textContent = this.getAttribute("text")
this.shadowRoot.appendChild(this.btn)
}
}
window.customElements.define("my-button", MyButton)
function change() {
document.getElementById("the-button").setAttribute("text", "Suns")
}