Web Components Part 1 — The Basics

What is a Web Component

Setup

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="app.js" defer></script>
</head>
<body></body>
</html>

A Hello World Component

class HelloWorld extends HTMLElement {
constructor() {
super()
this.innerHTML = `<h1>Hello World</h1>`
}
}
customElements.define("hello-world", HelloWorld)
<body>
<hello-world></hello-world>
</body>

ShadowDOM

class HelloWorld extends HTMLElement {
constructor() {
super()
//Add ShadowDOM to Component
this.attachShadow({ mode: "open" })
//Add template to shadowDOM
this.shadowRoot.innerHTML = `<h1>Hello World</h1>`
}
}
customElements.define("hello-world", HelloWorld)

Using Attributes(Props)

class HelloWorld extends HTMLElement {
constructor() {
super()
//Grabbing our Prop
const myProp = this.getAttribute("myProp")
console.log(myProp)
//Add ShadowDOM to Component
this.attachShadow({ mode: "open" })
//Add template to shadowDOM
this.shadowRoot.innerHTML = `<h1>Hello World</h1><h2>${myProp}</h2>`
}
}
customElements.define("hello-world", HelloWorld)
<body>
<hello-world myProp="hello"></hello-world>
</body>

Bottom Line

Alex Merced is a Full Stack Developer, learn more about his work at AlexMercedCoder.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store