Last active
November 28, 2023 19:30
-
-
Save kristoferjoseph/dd5d22018a0f7feedd4ee18f25a040a8 to your computer and use it in GitHub Desktop.
Single file MyMessage Custom Element pure function that enables adding tags dynamically in the browser with JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function MyMessage({ html, state }) { | |
const { attrs } = state | |
const { message='' } = attrs | |
return html` | |
<h1>${ message }</h1> | |
<script type="module"> | |
class MyMessage extends HTMLElement { | |
constructor() { | |
super() | |
const templateID = `${this.tagName.toLowerCase()}-template` | |
const template = document.getElementById(templateID) | |
if (template) { | |
this.template = template | |
} | |
else { | |
this.template = document.createElement('template') | |
this.template.innerHTML = `<h1></h1>` | |
this.template.setAttribute('id', templateID) | |
} | |
// Do not replace children if already present from SSR | |
if (!this.hasAttribute('enhanced')) { | |
this.replaceChildren(this.template.content.cloneNode(true)) | |
} | |
this.heading = this.querySelector('h1') | |
} | |
static get observedAttributes() { | |
return [ 'message' ] | |
} | |
attributeChangedCallback(name, oldValue, newValue) { | |
if (oldValue !== newValue) { | |
if (name === 'message') { | |
this.heading.textContent = newValue | |
} | |
} | |
} | |
} | |
customElements.define('my-message', MyMessage) | |
</script> | |
` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment