preface

Componentization has become the mainstream front-end development mode, and its reusability is a good news for many copy and paste engineers. Currently we implement componentization mainly relying on various frameworks such as Vue, React, Angular. These frameworks basically create their own set of development rules and writing syntax to enable developers to componentize their projects while following the rules of the browser. With the popularity of componentized frameworks in recent years, a suite of componentized solutions and support on native apis, Web Component, has been officially promoted.

Today we are going to take a brief look at Web Component.

The directory structure of this article is as follows:

  • What is a Web Component
  • Use the Web Component
    • Web Component core technology
    • Complete a simple component
    • The life cycle
    • A combination of Web Component and React
  • Write in the last

What is a Web Component

In this section, let’s take a quick look at what a Web Component is.

Web Components are a set of HTML and DOM features added to the W3C that allow developers to create reusable Components. Since Web Components is being pushed by the W3C, it is likely to become a standard feature in browsers in the near future.

Regardless of the official copywriting promoting the solution, the words “native” and “custom” tag are enough to make developers want to know about it.

Components written using Web Component are framework-independent. In other words, a Component library developed using Web Component is suitable for all frameworks and does not require different versions of Vue, React, and other frameworks like Antd.

After writing the Web Component, you can use it like this:

// Introduce custom components <script SRC ="/build/ mycom.js "></script> // use of components <my-com></my-com>Copy the code

The my-com tag is native and doesn’t need to go through the framework’s complicated logic and algorithms to compile into a DOM mount, or the browser itself will do some of the compiling for you, but it will certainly have a performance advantage over the framework’s implementation.

Use the Web Component

Now that you know the concept of Web Component, let’s look at how to use it.

Web Component core technology

Let’s start by looking at the core technologies involved in Web Component:

  • Custom Elements: A set of JavaScript apis that allow you to define Custom elements and their behavior, and then use them as needed in your user interface.

  • Shadow DOM: A set of JavaScript apis for attaching encapsulated “Shadow” DOM trees to elements (rendered separately from the main document DOM) and controlling their associated functionality. This way, you can keep the functionality of elements private so that they can be scripted and styled without fear of running afoul of the rest of the document.

  • HTML Templates (HTML templates) : The < template > and < slot > elements allow you to write tag templates that are not displayed on rendered pages. They can then be reused many times as a basis for custom element structures.

  • HTML Imports: Once you have defined a custom component, the easiest way to reuse it is to keep the definition details in a separate file and then use the import mechanism to import it into the page you want to actually use it. HTML imports are one such mechanism, although controversial – Mozilla disagrees with this approach at all and intends to implement a more appropriate one in the future.

Complete a simple component

Next, let’s look at the specific use of Web Component:

  1. Define custom components:

    class MyButton extends HTMLElement { constructor () { super(); const template = document.getElementById('mybutton'); const content = template.content.cloneNode(true); this.appendChild(content); }}Copy the code

    React class component (react class component)

  2. Defining a component template:

    <template id="mybutton">
        <button>Add</button>
    </template>
    Copy the code
  3. Registered components:

    window.customElements.define('my-button', MyButton);
    Copy the code
  4. Using components:

    <body>
        <my-button></my-button>
    </body>
    Copy the code

This completes a simple Web Component.

The life cycle

Like components in a normal framework, components in a Web Component have a life cycle to support more scenarios.

Common lifecycle methods are as follows:

  • connectedCallback

    This callback is called when the Web Component is added to the DOM and is executed only once. You can do some initialization in this callback, such as parameterizing the component’s style.

  • disconnectedCallback

    Executed when the Web Component is removed from the document DOM.

  • adoptedCallback

    Executed when the Web Component is moved to a new document.

  • attributeChangedCallback

    Executed when the monitored property changes.

A combination of Web Component and React

React can coexist with Web Components even if they become popular in the future. React is not a substitute. See – for details.

Use React in the Web Component

Usage:

class XSearch extends HTMLElement {
  connectedCallback() {
    const mountPoint = document.createElement('span');
    this.attachShadow({ mode: 'open' }).appendChild(mountPoint);

    const name = this.getAttribute('name');
    const url = 'https://www.google.com/search?q=' + encodeURIComponent(name);
    ReactDOM.render(<a href={url}>{name}</a>, mountPoint);
  }
}
customElements.define('x-search', XSearch);

Copy the code

Use the Web Component in React

Usage:

class HelloMessage extends React.Component {
  render() {
    return <div>Hello <x-search>{this.props.name}</x-search>!</div>;
  }
}
Copy the code

When using the Web Component in React, there is one particular point to note. Web Components typically expose imperative apis. For example, the Video component of Web Components might expose play() and Pause () methods. To access the imperative API of Web Components, you need to use refs to interact directly with DOM nodes. If you’re using third-party Web Components, the best solution is to write a React component that wraps the Web Components.

Events triggered by Web Components may not be delivered correctly through the React render tree. You need to manually add event handlers to the React component to handle these events.

Write in the last

This is a must-learn technique! Identification completed!