Skip to main content

Creating web components

Simple JavaScript approach

class SimpleCounter extends HTMLElement {
constructor() {
super();
this.count = 0;
this.attachShadow({ mode: 'open' });
}

connectedCallback() {
this.render();
this.shadowRoot.querySelector('button').addEventListener('click', () => {
this.count++;
this.render();
});
}

render() {
this.shadowRoot.innerHTML = `
<style>
:host {
display: block;
padding: 1rem;
border: 1px solid #ddd;
}
button {
background: #007bff;
color: white;
border: none;
padding: 0.5rem 1rem;
cursor: pointer;
}
</style>
<div>
<p>Count: ${this.count}</p>
<button>Increment</button>
</div>
`;
}
}

customElements.define('simple-counter', SimpleCounter);

Property and attribute handling

class MyComponent extends HTMLElement {
static get observedAttributes() {
return ['title', 'count'];
}

get title() {
return this.getAttribute('title') || '';
}

set title(value) {
this.setAttribute('title', value);
}

attributeChangedCallback(name, oldValue, newValue) {
if (oldValue !== newValue) {
this.render();
}
}
}