Skip to content

Counter: Lift HTML

CoreCounter.astro
<!-- render HTML that is going to be used by my-button -->
<my-button>
<button disabled>Clicks: 0</button>
</my-button>
<!-- load the implementation of the component -->
<script>
import "./core-counter";
</script>

(source)

core-counter.ts
import { liftHtml } from "@lift-html/core";
// define a custom element
const MyButton = liftHtml("my-button", {
init() {
const button = this.querySelector("button");
if (!button) throw new Error("<my-button> must contain a <button>");
button.disabled = false;
let count = 0;
button.onclick = () => {
count++;
button.textContent = `Clicks: ${count}`;
};
},
});
// define types for the custom element
declare module "@lift-html/core" {
interface KnownElements {
"my-button": typeof MyButton;
}
}

(source)

This is an example of HTML Web Component patterns and doesn’t use anything for reactivity. Initial component markup is generated by the server, then once client side implementation of custom element is loaded then disabled attribute is removed and click handler is added to the button. See also versions using @lift-html/solid and vanilla JavaScript.