🛠️

Creating Styled Tables with Web Components

Aug 27, 2024

Notes on Creating a Styled Table Using Web Components

Introduction

  • Speaker: Dom
  • Topic: Creating a styled table using web components
  • Features of the table:
    • Reusable component
    • CSS styling
    • Ability to update table data dynamically

HTML Structure

  • Custom component: <styled-table>
  • Use of data-headers attribute to define table headers.

Setup in VS Code

  1. Create a new file: index.js
  2. Set the script type to module in HTML: <script type="module" src="index.js"></script>
  3. Create a folder called components for your components.
  4. Create the following files:
    • table.js (JavaScript for the table component)
    • table.css (CSS for styling the table)

Table Component Implementation

Class Definition

  • Define class: export class Table extends HTMLTableElement
  • Use super() in constructor to call parent class.
  • Create a shadow root for encapsulated styling: this.attachShadow({ mode: 'open' });

Connected Callback

  • connectedCallback() runs when the element is inserted into the DOM.
  • Set inner HTML of shadow root to initial table structure: this.shadowRoot.innerHTML = `<table>`;

Register Custom Element

  • Import the table class in index.js: import { Table } from './components/table.js';
  • Define the custom element: customElements.define('styled-table', Table);

Building the Table Structure

Adding Table Headers

  • Use <thead>, <tr>, and <th> for headers.
  • Extract headers from data-headers attribute in connectedCallback(): const headers = this.dataset.headers.split(',').map(header => header.trim());
  • Inject headers into the table's header row.

CSS Integration

  • Link CSS file within the shadow root: const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = 'components/table.css'; this.shadowRoot.appendChild(link);
  • Write styles targeting table elements directly within shadow DOM.

Populating Table Data

Creating a Setter for Data

  • Add a set data method to handle incoming data: set data(newData) { ... }
  • Expect data format as a multi-dimensional array (array of arrays).
  • Create table rows dynamically based on the data provided.

Appending Data

  • Clear previous data in the table body before appending new data: tableBody.innerHTML = '';
  • Use appendChild() to insert new rows into the table body.

Conclusion

  • Custom methods can be added to enhance functionality (e.g., highlight a row).
  • Final encouragement to experiment with the component.
  • Reminder to like and subscribe for more content.