Web components are a way to build custom HTML tags. They can be created by extending existing HTML tags with JavaScript:
Building web components from scratch
class Greeter extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.innerHTML = "<h1>Hello, World!</h1>";
}
}
customElements.define("greeter-component", Greeter);
Shadow DOM
The Shadow DOM creates a separate DOM tree for the component, which is isolated from the main document DOM. Styles and scripts inside the shadow tree do not affect the main document, and vice versa.
An element can be open or closed
- if it is closed, it can’t be accessed with JavaScript.
Tools for building web components
Lit.js is a framework for building web components.
Existing frameworks
Many existing frameworks can export web components.
Usage in different frameworks
In React
Svelte Intro works nicely with web components.