Components Reusability; Attributes, Properties; Customization
Reusability
Web Components are inherently reusable. Once defined, you can use your custom element anywhere in your HTML just like a standard HTML element.
Attributes and Properties
Attributes and properties allow you to customize the behavior of your components.
Attributes
You can define custom attributes for your element and react to changes:
class UserCard extends HTMLElement {
static get observedAttributes() {
return ['name', 'avatar'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'name') {
this.querySelector('.name').textContent = newValue;
} else if (name === 'avatar') {
this.querySelector('img').src = newValue;
}
}
connectedCallback() {
this.innerHTML = `
<img src="${this.getAttribute('avatar') || 'default.jpg'}">
<p class="name">${this.getAttribute('name')}</p>
`;
}
}
customElements.define('user-card', UserCard);
Usage:
<user-card name="John Doe" avatar="john.jpg"></user-card>
Properties
You can also define properties on your custom element:
class MyCounter extends HTMLElement {
constructor() {
super();
this._count = 0;
}
get count() {
return this._count;
}
set count(value) {
this._count = value;
this.textContent = `Count: ${this._count}`;
}
connectedCallback() {
this.textContent = `Count: ${this._count}`;
}
}
customElements.define('my-counter', MyCounter);
Usage:
const counter = document.querySelector('my-counter');
counter.count = 5; // This will update the displayed count
Customization
Web Components can be customized in various ways:
- Attributes: As shown above, use attributes to pass data into your component.
- Slots: Use the
<slot>
element to define placeholders in your component that can be filled with custom content.
Example using slots:
class MyCard extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.innerHTML = `
<style>
.card { border: 1px solid #ccc; padding: 10px; }
.title { font-weight: bold; }
</style>
<div class="card">
<div class="title"><slot name="title">Default Title</slot></div>
<div><slot>Default content</slot></div>
</div>
`;
}
}
customElements.define('my-card', MyCard);
Usage:
<my-card>
<span slot="title">Custom Title</span>
<p>This is the main content of the card.</p>
</my-card>
This allows users of your component to customize its content while maintaining its structure and styling.
By leveraging these features—attributes, properties, and slots—you can create highly reusable and customizable Web Components that can be used across different projects and contexts.