Web Components: The Ultimate Guide to Building Custom Elements
What are Web Components?
Why Web Components?
It is our responsibility to write understandable code, HTML hasn’t been able to keep up with the rapid development pace at which other technologies have grown to build complex web applications.
With web components taking the HTML standards to the next level things are definitely going to change. They offer many benefits, like reusability, readability, interoperability, and maintainability, and thus form an indispensable set of tools for the developers.
Popular frameworks support Web Components.
React – As a developer, you are free to use React in your Web Components, or to use Web Components in react, or both.
Angular – Angular elements are Angular components packaged as custom elements.
Vue – Vue supports creating custom elements using exactly the same Vue components APIs.
Getting started with Web Components is easy.
Web Components are based on three core technologies:
- HTML templates: Custom user defined reusable HTML templates written with <template> and <slot> that are not rendered until called upon.
Creating a Web Component.
We can divide the steps involved in creating a Web Component like:
- Creating an ES6 class that extends HTMLElement to define the components API.
- Register the component to the browser's custom elements registry by calling the customElements.define() method available on the window object.
- Attach an instance of shadow DOM to the component (optional).
- Defining an HTML template for using <template> and attaching a clone to the component or the component's shadow DOM (optional).
Consuming the Web Components.
Consuming our new Web Component in React is pretty straightforward.
We will create a new Web Component with all the above knowledge and import it into the parent component where we would like to render it.
The process is quite similar to consuming our Web Component in Angular.
Angular by default will not recognize our custom HTML tag, to help Angular know our Web Component we need to add a schemas property to the @NgModule decorator and add CUSTOM_ELEMENTS_SCHEMA inside the schemas array.
This was just an introduction to Web Components. We can create them by creating elements from scratch as we did or by extending native HTML elements. They offer great benefits by improving the reusability, readability, maintainability, and interoperability of applications and save developers enormous amounts of time and frustration.
The browser support is very promising and will only improve in the years to come. We can use the polyfills to support the older browsers. I encourage you to keep exploring and experimenting. Happy coding!
Content Credit: Zameer Sheikh