Counter App

Let's build a more comprehensive counter application that demonstrates multiple Element features.

import { createSignal, html } from "@dmnchzl/element";

function Counter() {
  const [count, setCount] = createSignal(0);

  const increment = () => setCount(count() + 1);
  const decrement = () => setCount(count() - 1);
  const reset = () => setCount(0);

  return html`
    <div class="container">
      <h2>Count: ${count}</h2>
      <div class="btn-grp">
        <button onclick="${decrement}">-</button>
        <button onclick="${reset}">Reset</button>
        <button onclick="${increment}">+</button>
      </div>
    </div>
  `;
}

const root = document.getElementById("root") as HTMLElement;
root.appendChild(Counter());

Advanced Usage

This example shows how to use createComputed to derive values from signals:

import { createComputed, createSignal, html } from "@dmnchzl/element";

function Counter() {
  const [count, setCount] = createSignal(0);

  const isEven = createComputed(() => count() % 2 === 0);
  const parity = createComputed(() => isEven() ? 'Even' : 'Odd');
  const status = createComputed(() => {
    if (count() >= 0) return "Positive";
    return "Negative";
  });

  return html`
    <div class="container">
      <div class="flex flex-col">
        <h2>Count: ${count}</h2>
        <span class="parity">Parity: ${parity}</span>
        <span class="status">Status: ${status}</span>
      </div>

      <div class="btn-grp">
        <button onclick="${() => setCount(count() - 1)}">-</button>
        <button onclick="${() => setCount(0)}">Reset</button>
        <button onclick="${() => setCount(count() + 1)}">+</button>
      </div>
    </div>
  `;
}

document.body.appendChild(Counter());

Last updated