Skip to content

Counter: Solid

SolidCounter.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 "./solid-counter";
</script>

(source)

solid-counter.ts
import { liftSolid } from "@lift-html/solid";
import { createEffect, createSignal } from "solid-js";
// define a custom element
const MyButton = liftSolid("my-button", {
init() {
const button = this.querySelector("button");
if (!button) throw new Error("<my-button> must contain a <button>");
button.disabled = false;
const [count, setCount] = createSignal(0);
button.onclick = () => setCount(count() + 1);
createEffect(() => {
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 uses SolidJS reactivity (signals). 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/core and vanilla JavaScript.