Document Fragment with Kor UI
01/15/2022, SatDynamically Adding Lit Elements into Page
Lit elements are an implementation of web components. Lit elements are useful because it encourages component reuse across different JavaScript frameworks, which leads to reduced development time.
The traditional usage of Lit elements / web components involves defining the component inside your html page, however there might be instances where you do not wish to modify the html page by introducing the web component markup. The introduced web components might serve only as an assistive means for using the page, but the html export of the page must remain immaculate.
Since the page can not be modified during the initial definition, it will not be initially rendered. This will mean that dom manipulation will need to be employed after the fact and a way to achieve this is to use a document fragment.
If we were to use a web component library that is built on top of the default Lit elements, such as the Kor UI library, the Lit element library will also need to be used because the Kor UI library does not offer low-level dynamic page manipulation capabilities.
The Lit element library will allow for the creation of a new wrapper web component that renders the Kor UI element inside a document fragment using the Range.createContextualFragment() method. The createContextualFragment
method will take in a raw string and render it as live html.
After this, when a new custom Lit element is defined and registered, it can be inserted into a dom element of your choice.
The below example shows the complete usage:
<link
rel="stylesheet"
type="text/css"
href="https://unpkg.com/@kor-ui/kor@1.9.1/kor-styles.css"
/>
<script type="module">
import { LitElement, html } from
'https://unpkg.com/lit@2.1.1/index.js?module';
import 'https://unpkg.com/@kor-ui/kor@1.9.1/components/button/index.js?module';
// Wrap the Kor Button component
class KorButtonWrap extends LitElement {
render() {
return html `${
document
.createRange()
.createContextualFragment(`
<kor-button label='${this.label}' color='primary'></kor-button>
`)
}`;
}
}
// Register the Kor button into a custom wrapper element
customElements.define('kor-button-wrap', KorButtonWrap);
// Create the custom wrapper element for the button
let korButtonWrap = document.createElement('kor-button-wrap');
// Define text dynamically after the creation of the wrapped kor button
korButtonWrap.label = 'some text'
// Get div container for appending the element
let container = document.getElementById('container');
// Insert the wrapped kor button into a div container
container.appendChild(korButtonWrap);
</script>
<div id="container"></div>
Online example: https://jsfiddle.net/1vczbamp/