The concept of reusable components can clearly be seen in component-based frameworks like React and Vue.
This introduces modularity into our UI development, especially in cases where several screens or pages of a web project have shared components.
But how can we achieve this without a solid grasp of these component-based frameworks and a strong knowledge of JavaScript?
I thought about this after I worked on a 30-page website for a bank sometime back, before I knew how to use Vue.js, React, or PHP’s famous includes
function.
I was left with no choice other than to serially copy and paste the same header and footer sections into all 30 HTML files. Stressful, huh?
Definitely, because for every change made to either the header or footer, the same had to be done for all the other pages.
This frustrated me and got me to start thinking if there was a way that a page in pure HTML could have components. It would make work easier for people like my past self that just know HTML, CSS, and vanilla JavaScript.
In this article, I will quickly take you through how to build JavaScript components and call each component in your HTML.
Imagine we have a website of five pages all having the same header and the same footer.
The first step is to copy the existing header HTML section and place it in a class object in JavaScript. Then, render it to the page using innerHTML
:
class Header extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<nav>
{*Header code goes here *}
</nav>
`;
}
}
class Footer extends HTMLElement {
connectedCallback() {
this.innerHTML = `
<footer>
{*footer code goes here *}
</footer>
`;
}
}
The JavaScript file defines a class called Header
which extends the generic HTMLElement class.
connectedCallback()
is invoked each time the custom element/component is appended into a document-connected element.
The difference between using connectedCallback()
and constructor()
is that constructor()
is called when the element is created and connectedCallback()
is called after the element is attached to the DOM.
But either one works for what we want to achieve.
Finally, this.innnerHTML
displays the content in the HTML tag.
#javascript #html #react #vue #web-development