Web components are encapsulated UI components written in JS/HTML/CSS without the use of frameworks. Web components allow native HTML elements to be extended and composed with custom javascript funcitonality and isolated styles.
In the example below, I declare a custom element which will render a codeblock. In fact, the code is rendered inside an instance of that very custom component! This custom component extends the HTML div element and formats its inner html as a string. A copy button is provided to add the snippet to your clipboard.
${this.innerHTML}` const placeholder = document.createElement('div'); placeholder.insertAdjacentHTML('afterbegin', template); const node = placeholder.firstElementChild; this.shadowRoot.appendChild(node); const button = document.createElement('button'); button.innerText = 'Copy'; this.shadowRoot.appendChild(button); button.addEventListener('click', () => { navigator.clipboard.writeText(this.textContent) }); } } window.customElements.define('code-block', CodeBlock)
Once defined and registered on the page, the custom component can be freely used. For instance, adding the following to the web page
Hello World
Hello World
After starting this sandbox I found a very similar article on css-tricks which I leveraged.
I also made use of some Google developer articles on the subject.