Preact is not only an efficient alternative to React but also provides native support for Web Components. This allows developers to harness the power of Web Components while benefiting from Preact’s performance advantages.
Defining Custom Elements
Creating a Custom Element
Use Preact’s define function to create a custom element.
import { h, define } from 'preact';
class MyElement extends HTMLElement {
connectedCallback() {
this.render();
}
render() {
this.attachShadow({ mode: 'open' }).append(
h('div', null, 'Hello, Web Component!')
);
}
}
define('my-element', MyElement);Using Shadow DOM
Purpose of Shadow DOM
Shadow DOM allows you to create an isolated DOM tree for custom elements, encapsulating styles and logic to prevent interference from external styles.
Creating Shadow DOM
Create a Shadow DOM in the connectedCallback.
connectedCallback() {
const shadow = this.attachShadow({ mode: 'open' });
shadow.append(h('div', null, 'Hello, Shadow DOM!'));
}Interacting with Preact Components
Using Custom Elements in Preact
Custom elements can be used as standard HTML tags in Preact.
import { h } from 'preact';
function App() {
return (
<div>
<my-element></my-element>
</div>
);
}Passing Attributes from Preact to Web Components
Pass attributes to custom elements as you would with regular HTML tags.
function App() {
return (
<div>
<my-element name="World"></my-element>
</div>
);
}Receive attributes in the Web Component:
class MyElement extends HTMLElement {
static get observedAttributes() {
return ['name'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'name') {
this.render(newValue);
}
}
render(name) {
this.shadowRoot.innerHTML = `<div>Hello, ${name}!</div>`;
}
}Leveraging Web Components’ Advantages
Style Encapsulation
The Shadow DOM feature of Web Components encapsulates styles, ensuring they are unaffected by external styles.
Reusability and Composition
Custom elements can be reused and composed like standard HTML elements, enhancing code reusability and modularity.
Summary
Preact’s support for Web Components offers developers a new way to build UIs, combining the encapsulation capabilities of Web Components with Preact’s performance benefits. By defining custom elements, using Shadow DOM, and enabling interaction between Web Components and Preact components, you can create modular, reusable, and high-performance web applications. As you deepen your understanding of Web Components and Preact, you can explore advanced topics such as communicating with custom events, optimizing performance, and applying these techniques in real-world projects. Through practicing these concepts, you’ll be able to build web applications that adhere to modern web standards while delivering exceptional performance.



