Whenever we use any of those Front-end frameworks present in the market, like React, Angular, Vue, etc., we mostly break our User Interface into smaller manageable parts called the components. But have you ever thought that whether or not can we divide our UI into components without using these frameworks?
The answer to it is yes, and what helps us in doing so is Web Components.
Web Components are the collection of certain Web APIs that allow us to divide our User Interface into smaller blocks called components. It helps us to encapsulate the functionality of the component into an HTML tag, which we can then use anywhere in our web app.
Now you might think that it sounds great, but we might have to install something?
Another interesting feature of web components is that they can, later on, be used with other frameworks like React, Angular, and Vue.
To provide you the functionality encapsulated within some HTML tags the Web Components make use of 3 main technologies. These technologies help in creating versatile components without the risk of them colliding at any point in our Web App.
These 3 main technologies are:-
Some of these lifecycle methods are:-
- constructor():- Behaves similar to what the constructor in normal Object-Oriented Programming Languages behave. The constructor lifecycle method gets called when an instance of our element is created. The most common things to do within the constructor are initializing the state, adding event listeners, etc.
- connectedCallback():- This lifecycle method is called when our element is inserted into the DOM(Document Object Model).
- disconnectedCallback():- This lifecycle method is called anytime when our element is removed from the DOM.
- attributeChangedCallback():- This lifecycle method is called when any attribute is either added, removed, updated, or replaced in our element. This lifecycle method accepts 3 parameters attributeName, oldValue, and newValue.
2. Shadow DOM:- Shadow DOM allows us to encapsulate a "shadow" DOM for our element. This encapsulates styles and markups for our self-contained components. This gives our element its own identity which makes it separate from the overall DOM of the web page.
The Shadow DOM helps in preventing the collision of styles and features of our component from the overall global styling and feature of the page. The shadow DOM is created by using the attachShadow method with our element name:
3. HTML Templates:- The HTML Templates allow us to define the encapsulated markup of the web component. The template tag stores the markup on the page and can include both HTML and CSS for our component. Slots are used to add custom text to our component. Both template and slot enable us to write markups that are not displayed on the rendered page.
Let's now create our own Web Component, refer to this blog to get detailed steps on how to create your own Web Component.