DEV Community

xRdev_38
xRdev_38

Posted on

Using Web Components in Your JavaScript Project

Using Web Components in Your JavaScript Project

Web Components provide a standard way to create reusable components, independent of frameworks.

Example: Create a Simple Custom Element

class HelloWorld extends HTMLElement {
  connectedCallback() {
    this.innerHTML = `<b>Hello, <span>${this.getAttribute('name') || 'World'}</span>!</b>`;
  }
}
customElements.define('hello-world', HelloWorld);
Enter fullscreen mode Exit fullscreen mode

Usage:

<hello-world name="Frontend Dev"></hello-world>
Enter fullscreen mode Exit fullscreen mode

Practical Use: Web Components and Frameworks

You can use a Web Component in Angular, Vue, or React:

Angular (HTML):

<hello-world name="Angular User"></hello-world>
Enter fullscreen mode Exit fullscreen mode

React:

<hello-world name="React User"></hello-world>
Enter fullscreen mode Exit fullscreen mode

Tip

  • Great for sharing widgets across projects.
  • Ideal for framework-agnostic design systems.

Bonus

  • Add custom events for communication:
this.dispatchEvent(new CustomEvent('hello', { detail: { name: this.getAttribute('name') } }));
Enter fullscreen mode Exit fullscreen mode

Conclusion

Web Components let you encapsulate, share, and reuse your components anywhere!

Top comments (0)