Using Web Components in Your JavaScript Project
Web Components provide a standard way to create reusable components, independent of frameworks.
Example: Create a Simple Custom Element
class HelloWorld extends HTMLElement {
connectedCallback() {
this.innerHTML = `<b>Hello, <span>${this.getAttribute('name') || 'World'}</span>!</b>`;
}
}
customElements.define('hello-world', HelloWorld);
Usage:
<hello-world name="Frontend Dev"></hello-world>
Practical Use: Web Components and Frameworks
You can use a Web Component in Angular, Vue, or React:
Angular (HTML):
<hello-world name="Angular User"></hello-world>
React:
<hello-world name="React User"></hello-world>
Tip
- Great for sharing widgets across projects.
- Ideal for framework-agnostic design systems.
Bonus
- Add custom events for communication:
this.dispatchEvent(new CustomEvent('hello', { detail: { name: this.getAttribute('name') } }));
Conclusion
Web Components let you encapsulate, share, and reuse your components anywhere!
Top comments (0)