Web Components
๐ Covered in this chapter:
Web Components Standard ยท Custom Elements (customElements.define) ยท Shadow DOM Encapsulation ยท Templates & Slots ยท Form-Associated Custom Elements ยท Web Components vs React
Welcome to Phase 12 (Chapter 33): Web Components! Build native encapsulated UI components using Custom Elements, Shadow DOM, and HTML Templates.
1Custom Web Component Class Example
HTML + JS โ Custom Web Component
โถ Run in HTML Editor
<user-card name="Balaji" role="Developer"></user-card>
<script>
class UserCard extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<style>
.box { padding:15px; border:1px solid #f97316; border-radius:6px; background:#141922; color:#fff; }
h4 { color:#f97316; margin:0 0 5px 0; }
</style>
<div class="box">
<h4>${this.getAttribute('name')}</h4>
<p>${this.getAttribute('role')}</p>
</div>
`;
}
}
customElements.define('user-card', UserCard);
</script>