json-to-html-table-with-lit

JSON to HTML Table with Lit

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "json-to-html-table-with-lit" with this command: npx skills add rodydavis/skills/rodydavis-skills-json-to-html-table-with-lit

JSON to HTML Table with Lit

In this article I will go over how to set up a Lit web component and use it to create a HTML Table from json url or inline json.

TLDR The final source here and an online demo.

Prerequisites 

  • Vscode

  • Node >= 16

  • Typescript

Getting Started 

We can start off by navigating in terminal to the location of the project and run the following:

npm init @vitejs/app --template lit-ts

Then enter a project name lit-html-table and now open the project in vscode and install the dependencies:

cd lit-html-table npm i lit npm i -D @types/node code .

Update the vite.config.ts with the following:

import { defineConfig } from "vite"; import { resolve } from "path";

export default defineConfig({ base: "/lit-html-table/", build: { lib: { entry: "src/lit-html-table.ts", formats: ["es"], }, rollupOptions: { input: { main: resolve(__dirname, "index.html"), }, }, }, });

Template 

Open up the index.html and update it with the following:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/src/favicon.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>JSON to Lit HTML Table</title> <script type="module" src="/src/lit-html-table.ts"></script> </head>

<body> <lit-html-table src="https://jsonplaceholder.typicode.com/posts"> <!-- <span slot="title" style="color: red;">Title</span> --> <!-- <script type="application/json"> [ { "id": "0", "name": "First Item" } ] </script> --> </lit-html-table> </body> </html>

We are passing a src attribute to the web component for this example but we can also add a script tag with the type attribute set to application/json  with the contents containing the json.

If any table header cell needed to be replaced an element can be provided with the slot name set to the key in the json object.

Web Component 

Before we update our component we need to rename my-element.ts  to lit-html-table.ts

Open up lit-html-table.ts and update it with the following:

import { html, css, LitElement } from "lit"; import { customElement, property } from "lit/decorators.js";

type ObjectData = { [key: string]: any };

@customElement("lit-html-table") export class LitHtmlTable extends LitElement { @property() src = "";

data?: ObjectData[];

static styles = css tr { text-align: var(--table-tr-text-align, left); vertical-align: var(--table-tr-vertical-align, top); padding: var(--table-tr-padding, 10px); } ;

render() { // Check if data is loaded if (!this.values) { return html&#x3C;slot name="loading">Loading...&#x3C;/slot>; } // Check if items are not empty if (this.values.length === 0) { return html&#x3C;slot name="empty">No Items Found!&#x3C;/slot>; } // Convert JSON to HTML Table return html &#x3C;table> &#x3C;thead> &#x3C;tr> ${Object.keys(this.values[0]).map((key) => { const name = key.replace(/\b([a-z])/g, (_, val) => val.toUpperCase() ); return html<th> <slot name="${key}">${name}</slot> </th>; })} &#x3C;/tr> &#x3C;/thead> &#x3C;tbody> ${this.values.map((item) => { return html <tr> ${Object.values(item).map((row) => { return html&#x3C;td>${row}&#x3C;/td>; })} </tr> ; })} &#x3C;/tbody> &#x3C;/table> ; }

async firstUpdated() { await this.fetchData(); }

// Download the latest json and update it locally async fetchData() { let _data: any; if (this.src.length > 0) { // If a src attribute is set prefer it over any slots _data = await fetch(this.src).then((res) => res.json()); } else { // If no src attribute is set then grab the inline json in the slot const elem = this.parentElement?.querySelector( 'script[type="application/json"]' ) as HTMLScriptElement; if (elem) _data = JSON.parse(elem.innerHTML); } this.values = this.transform(_data ?? []); this.requestUpdate(); }

transform(data: any) { return data; } }

We have defined a few CSS Custom Properties to style the table cell but many more can be added here.

If everything goes well run the command npm run dev and the follow should appear:

Editing 

What if we wanted to support editing of any cell? With Lit and Web Components we can progressively enhance the experience without changing the html.

At the top of the class add the following boolean property:

@property({ type: Boolean }) editable = false;

Now update the tbody tag in the render method:

<tbody> ${this.values.map((item, index) => { return html &#x3C;tr> ${Object.entries(item).map((row) => { return html<td> ${this.editable ? html&#x3C;input value="${row[1]}" type="text" @input=${(e: any) => { const value = e.target.value; const key = row[0]; const current = this.values![index]; current[key] = value; this.values![index] = current; this.requestUpdate(); this.dispatchEvent( new CustomEvent("input-cell", { detail: { index: index, data: current, }, }) ); }} /> : html${row[1]}} </td>; })} &#x3C;/tr> ; })} </tbody>

By checking to see if the editable  and if true  return an input with an event listener to update the data and dispatch an input  event.

Add the editable  attribute to the index.html :

<lit-html-table editable> ... </lit-html-table>

After a reload the table should look like this and any cell can be edited.

An event listener can be added just before the closing body  tag in index.html to grab the latest values or cell information:

<script> const elem = document.querySelector("lit-html-table"); elem.addEventListener( "input-cell", (e) => { // Index and data for the individual cell const { index, data } = e.detail; // New array of json items const values = elem.values; }, false ); </script>

This can be taken farther by checking for the type of the value and returning a color, number or checkbox input.

Conclusion 

If you want to learn more about building with Lit you can read the docs here. There is also an example on the Lit playground here.

The source for this example can be found here.

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

General

flutter-control-and-screenshot

No summary provided by upstream source.

Repository SourceNeeds Review
General

install-flutter-from-git

No summary provided by upstream source.

Repository SourceNeeds Review
General

how-to-build-a-native-cross-platform-project-with-flutter

No summary provided by upstream source.

Repository SourceNeeds Review
General

how-to-build-a-webrtc-signal-server-with-pocketbase

No summary provided by upstream source.

Repository SourceNeeds Review