Brijesh's Git Server — web-components-demo @ 082a49484ec39d386b9603423b0ee818e51f514f

this is for demo, will be deleted soon

batman
Brijesh Wawdhane brijesh@wawdhane.com
Sun, 15 Sep 2024 22:14:48 +0530
commit

082a49484ec39d386b9603423b0ee818e51f514f

3 files changed, 62 insertions(+), 0 deletions(-)

jump to
A component.js

@@ -0,0 +1,8 @@

+const myComponentTemplate = ` + <div class="min-w-96 mb-4 p-4 border border-gray-300 rounded-lg"> + <h2 class="text-xl font-bold mb-2">{{title}}</h2> + <p class="text-gray-600">{{content}}</p> + </div> +`; + +createWebComponent("my-component", myComponentTemplate, ["title", "content"]);
A helper.js

@@ -0,0 +1,27 @@

+function createWebComponent(tagName, template, props = []) { + class CustomElement extends HTMLElement { + constructor() { + super(); + this.render(); + } + + static get observedAttributes() { + return props; + } + + attributeChangedCallback(name, oldValue, newValue) { + this.render(); + } + + render() { + const html = template.replace(/{{(\w+)}}/g, (match, prop) => { + return this.getAttribute(prop) || ""; + }); + this.innerHTML = html; + } + } + + customElements.define(tagName, CustomElement); +} + +window.createWebComponent = createWebComponent;
A index.html

@@ -0,0 +1,27 @@

+<!doctype html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>Web Component Example</title> + <script src="https://cdn.tailwindcss.com"></script> + + <script src="helper.js"></script> + <script src="component.js" defer></script> + </head> + <body> + <div class="container mx-auto p-4"> + <h1 class="text-lg font-semibold mb-4">Web Components Demo</h1> + <div class="flex flex-col lg:flex-row gap-4"> + <my-component + title="Welcome" + content="This is a custom web component" + ></my-component> + <my-component + title="Another Example" + content="This is reusable" + ></my-component> + </div> + </div> + </body> +</html>