[JavaScript] Create reusable component in separate HTML file

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.

  1. 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
  2. Create HTML content.
    Open uuid-generator-component.html and update content as below.

    <div>
    This is UUID generator.
    </div>
  3. 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));
        }
    }
  4. 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>
  5. Test
    Run application in debug mode, and check the render result. Expected there are 2 elements return.
About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.