Concept Explanation
Imagine if HTML didn't have a <button> tag. You would have to make one using <div> and a lot of messy JS. Web Components let you create your own real HTML tags like <user-card> or <video-player>.
The best part? They work in any framework (React, Vue, Angular) or even in a plain HTML file without any framework at all.
Syntax or Core Structure
The Class Definition
class MyGreeter extends HTMLElement {
constructor() {
super(); // Always call super first!
console.log("I am born!");
}
connectedCallback() {
this.innerHTML = "<h1>Hello from a Custom Element!</h1>";
}
}
// Register the tag with the browser
customElements.define('my-greeter', MyGreeter);
Real World Example
Company Branding: A large company like Google or Adobe has thousands of different websites. They build their "Official Buttons" and "Auto-complete Boxes" as Web Components. This ensures that every site looks the same, regardless of whether the team uses React or just plain HTML.
Practice Exercises
- The Tag Maker: Create a custom element
<color-box>that displays a 100x100 square of a specific color. - The Capital Rule: Research why custom elements MUST have a hyphen (
-) in their name (e.g.,<my-tag>, not<mytag>). - The Attribute Watcher: Research
attributeChangedCallbackand write a component that updates its text whenever you change itsnameattribute in the inspector.