In HTML, we can use tag <Template> to create reusable component, but it is limited in single. In this article, it will show how to create JavaScript component in seperate HTML / JS files.
This demo will name component uuid-generator as example.
- Create component directories.
Use command below to create directories and related files.set componentDirectory=components/uuid-generator mkdir -p $componentDirectory touch $componentDirectory/uuid-generator-component.js touch $componentDirectory/uuid-generator-component.html
- Create HTML content.
Open uuid-generator-component.html and update content as below.<div> This is UUID generator. </div>
- Create JS component.
Open uuid-generator-component.js and update content as below.export class UUIDGeneratorComponent { render(elementId) { fetch("components/uuid-generator/uuid-generator-component.html") .then(response => response.text()) .then(templateHtml => { const element = document.getElementById(elementId); element.innerHTML = templateHtml; }) .catch(error => console.error("Error occurred when render template.", error)); } }
- Call component.
In corresponding HTML file, update content as below. In this case, there are 2 elements to be render, which named test1 and test2.<div id="test1"></div> <div id="test2"></div> <script> import { UUIDGeneratorComponent } from "./components/uuid-generator/uuid-generator-component.js"; document.addEventListener("DOMContentLoaded", () => { const uuidGeneratorComponent = new UUIDGeneratorComponent(); uuidGeneratorComponent.render("test1"); const uuidGeneratorComponent2 = new UUIDGeneratorComponent(); uuidGeneratorComponent2.render("test2"); }); </script>
- Test
Run application in debug mode, and check the render result. Expected there are 2 elements return.
Leave a Reply