Web Components are a set of web platform APIs that allow developers to create new custom, reusable, encapsulated HTML tags for web pages and web apps. Web components are to the web what components heralded in modern UI development frameworks like Vue, Angular, React; modularity, reusability, and encapsulation.
Web Components consist of three main technologies:
class MyElement extends HTMLElement {
constructor() {
super();
}
}
customElements.define('my-element', MyElement);
const shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = `
<style>
.my-style { /* styles go here */ }
</style>
<div class="my-style">Hello, Shadow DOM!</div>
`;
<template id="myTemplate">
<slot name="user"></slot>
</template>
Let's write a basic web component that displays a simple message.
// Define a class for the component
class SimpleGreeting extends HTMLElement {
// Always call super first in the constructor
constructor() {
super();
// Write element functionality in here
this.innerHTML = `<p>Hello, Web Components!</p>`;
}
}
// Define the new element
customElements.define('simple-greeting', SimpleGreeting);
This component can now be used anywhere in your HTML file, just like a regular HTML tag:
<simple-greeting></simple-greeting>
When you load your HTML, you should see "Hello, Web Components!" displayed in the paragraph.
Let's enhance the above web component to use Shadow DOM so that its styles and behavior don't affect other parts of the application.
class ShadowGreeting extends HTMLElement {
constructor() {
super();
let shadow = this.attachShadow({mode: 'open'});
let wrapper = document.createElement('div');
wrapper.setAttribute('class', 'shadow-greeting');
wrapper.innerHTML = 'Hello from Shadow DOM!';
let stylesheet = document.createElement('style');
stylesheet.textContent = `
.shadow-greeting {
font-weight: bold;
color: blue;
}`;
shadow.appendChild(stylesheet);
shadow.appendChild(wrapper);
}
}
customElements.define('shadow-greeting', ShadowGreeting);
In this web component, we've encapsulated the styling and functionality using Shadow DOM so that it won't affect other areas of your application.
Web Components represent a significant shift in web development, allowing for greater modularity, reusability, and encapsulation. By mastering the use of Web Components, developers can produce more efficient, clean, and maintainable code.
1500 words authored by Gen-AI! So please do not take it seriously, it's just for fun!