Sunday, September 20, 2020

Why should stick to react

The purpose of Web Components

Web Components is a set of different technologies that are used together to help developers write UI elements that are semantic, reusable, and properly isolated.

A custom element is a way of defining an HTML element by using the browser’s JavaScript API. A custom element has its own semantic tag and lifecycle methods, similar to a React component

Shadow DOM is a way of isolating DOM elements and scoping CSS locally to prevent breaking changes from affecting other elements.

HTML template is a way of writing invisible HTML elements that acts as a template that you can operate on using JavaScript’s query selector.


The shadow DOM example

Shadow DOM allows you to write HTML elements that were scoped from the actual DOM tree. It’s attached to the parent element, but won’t be considered as its child element by the browser. Here is an example:



Any code you write inside the shadow DOM will be encapsulated from the code outside of it. One of the benefits of using shadow DOM is that any CSS code you write will be local and won’t affect any element outside of it.

When you inspect the shadow element, you’ll see it marked with #shadow-root:


The browser will return null when you try to select the shadow button with document.getElementById(‘shadow-button’) . You need to select the parent element and grab its shadowRoot object first:


const el = document.getElementById('example').shadowRoot

el.getElementById('shadow-button') 


HTML template example

HTML template allows you to write invisible HTML elements that you can iterate through with JavaScript in order to display dynamic data. To write one, you need to wrap the elements inside a <template> tag:


<template id="people-template">

  <li>

    <span class="name"></span> &mdash; 

    <span class="age"></span>

  </li>

</template>

<ul id="people"></ul>




References

https://blog.bitsrc.io/web-component-why-you-should-stick-to-react-c56d879a30e1



No comments:

Post a Comment