Building a Web Component without JS Frameworks
We are in the era of the components. and they are being used in almost all the web pages and applications of the moment; Facebook created its own library to make its web components, Google also created its own framework called Angular and there are many more libraries to make these web components. In this article, we are going to talk about web components and how to build one without using any framework like ReactJS or VueJS.
¿What is a web component?
A web component is an element that allows you to encapsulate the css, js and html code in a single element. By default, browsers bring several web components such as <input> <p> <h1> <button> These are all web components that are integrated by default in the browser and are interpreted with their own styles and javascript code.
¿How to create my own web component without using a library?
To create a web component, we must use the class CustomElementRegistry which allows us to use its define () method, which requires two arguments and has an optional one:
DOMString:
Required argument must be the name that will be given to the web component. The name is, for example, in the case of the default components ‘input’ or ‘p’. In our case, we will create a component with the name “Hola mundo”. The names of the components must be in lowercase and the spaces must be replaced by a hyphen, so the name of our component would be “hola-mundo”
class:
Like the DOMString argument, this argument is also required. In it, we must define the name of the previously created class in which we program the functionality of the component.
extends:
This optional argument helps us to specify that our component extends from an existing component between pre-built and defined components in the browser.
Our component would look like this:
// Definimos la clase HolaMundo: class HolaMundo extends HTMLElement { constructor() { // Se debe llamar super() siempre que se sobreescriba el constructor // debe ser antes de cualquier otro código super(); // Código del componente web puede ser escrito después de esta línea this.innerHTML = "<h1>Hola Mundo</h1>"; console.log("Hola Mundo Cargado"); }; }; // Agregamos el componente a los elementos personalizados o propios customElements.define('hola-mundo', HolaMundo);
To use the web component we must only write in the html code:
<hola-mundo></hola-mundo>
If you want to see the component working, you can see it in the following link: https://codepen.io/lcmartinez/pen/Oqobea
Using web components without frameworks is useful in small projects that do not require very advanced features. However, technology promises and, in my opinion, they will be used much more in the future.
Resources:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement
https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements