DEV Community

Lucas Pereira de Souza
Lucas Pereira de Souza

Posted on

Creating Web Components

logotech

## Building Powerful Web Components with Pure JavaScript

In the world of modern web development, modularity and code reuse are essential. Web components offer an elegant solution for creating complex user interfaces in an organized and easy-to-maintain way. In this post, we'll explore how to build robust web components using pure JavaScript, Shadow DOM, and how to package your component so it can be used on any website.

Why Web Components?

  • Reusability: Create components that can be used in multiple parts of your site or in different projects.
  • Encapsulation: Shadow DOM ensures that your component's CSS and JavaScript do not interfere with the rest of the page and vice versa.
  • Maintenance: Easy to update and modify individual components without affecting the rest of the application.
  • Organization: Divides your UI into smaller, manageable parts.

Creating a Web Component with Pure JavaScript

Let's build a simple component: a custom button.

class MeuBotao extends HTMLElement {
  constructor() {
    super();
    this.shadow = this.attachShadow({ mode: 'open' }); // 'open' or 'closed'
  }

  connectedCallback() {
    this.render();
    this.addEventListener('click', () => {
      this.onClick();
    });
  }

  onClick() {
    alert('Botão clicado!');
  }

  render() {
    this.shadow.innerHTML = `
      <style>
        button {
          background-color: #4CAF50;
          border: none;
          color: white;
          padding: 10px 20px;
          text-align: center;
          text-decoration: none;
          display: inline-block;
          font-size: 16px;
          margin: 4px 2px;
          cursor: pointer;
          border-radius: 5px;
        }
      </style>
      <button>
        <slot>Clique Aqui</slot>
      </button>
    `;
  }
}

customElements.define('meu-botao', MeuBotao);
Enter fullscreen mode Exit fullscreen mode

Code Analysis:

  1. class MeuBotao extends HTMLElement: Creates a class that extends HTMLElement, the base for all web components.
  2. constructor(): In the constructor, we call super() to initialize the component and this.attachShadow({ mode: 'open' }) to create the Shadow DOM. mode: 'open' allows access to the Shadow DOM from outside the component (for debugging and modification purposes). mode: 'closed' prevents access.
  3. connectedCallback(): This method is called when the component is inserted into the DOM. In it, we call this.render() to render the content and add an event listener for the click.
  4. onClick(): A simple method that displays an alert when the button is clicked.
  5. render(): Defines the HTML and CSS of the component within the Shadow DOM. We use <slot> to allow content to be injected by the user of the component.
  6. customElements.define('meu-botao', MeuBotao): Registers the component with the browser, associating the tag <meu-botao> with our class.

Using the Shadow DOM for Encapsulation

The Shadow DOM creates a separate and isolated DOM within your component. This means that:

  • Styles: Styles defined within the Shadow DOM do not affect the rest of the page, and styles from the page do not affect the component.
  • JavaScript: Variables and functions within the Shadow DOM are not accessible from outside, and vice versa (unless you explicitly design them to be).

Distributing your Package

To make your component reusable on other sites, you can package and distribute it. Options include:

  1. Creating a JavaScript file: Simply create a .js file containing your component code. Incorporate it into other sites using the <script> tag.

    <script src=\"meu-botao.js\"></script>
    <meu-botao>Clique Aqui</meu-botao>
    
  2. Using a package manager (npm/yarn):

*   **Initialize the project:** `npm init -y` (or `yarn init -y`)
*   **Create the component file** (as in the example above).
*   **Create an `index.js` file** (or the name you prefer) that exports your component.
Enter fullscreen mode Exit fullscreen mode
    ```javascript
    import './meu-botao.js'; // Imports the component file
    ```
Enter fullscreen mode Exit fullscreen mode
*   **In `package.json`:**
    *   Define the `main` field for the main file (e.g., `\"main\": \"index.js\"`).
    *   **Publish to npm** (optional): `npm publish` (requires an npm account).
*   **To use in another project:** `npm install seu-pacote-do-componente`
*   **Import and use:**
Enter fullscreen mode Exit fullscreen mode
    ```javascript
    import 'seu-pacote-do-componente';
    // ...
    <meu-botao>Clique Aqui</meu-botao>
    ```
Enter fullscreen mode Exit fullscreen mode
  1. CDN (Content Delivery Network): Host your JavaScript file on a CDN (like jsDelivr or unpkg). This allows you to use your component on any site simply by adding a <script> tag pointing to the CDN URL.

    <script src=\"https://cdn.jsdelivr.net/npm/seu-pacote-do-componente@1.0.0/meu-botao.js"></script>
    <meu-botao>Clique Aqui</meu-botao>
    

Final Considerations

Web components, along with Shadow DOM, offer a powerful and organized way to build user interfaces. By encapsulating your code and styles, you ensure that your component is reusable, easy to maintain, and does not conflict with other parts of your site. Distributing your component, whether through simple JavaScript files, package managers, or CDNs, allows you to share your work and create an ecosystem of reusable components. Explore, experiment, and build!

Top comments (0)