Your First App

Let's build a simple counter application to demonstrate Element's core features.

Step 1: Setup the State

/* App.ts */
import { createSignal } from "@dmnchzl/element";

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

Step 1.5: Complexify the State

/* App.ts */
import { createComputed, createSignal } from "@dmnchzl/element";

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

  const status = createComputed(() => {
    if (count() >= 0) return "Positive";
    return "Negative";
  });
}

Step 2: Create Helper Functions

/* App.ts */
import { createComputed, createSignal } from "@dmnchzl/element";

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

  const status = createComputed(() => {
    if (count() >= 0) return "Positive";
    return "Negative";
  });

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

Step 3: Create the Template

/* App.ts */
import { createComputed, createSignal, html } from "@dmnchzl/element";

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

  const status = createComputed(() => {
    if (count() >= 0) return "Positive";
    return "Negative";
  });

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

  return html`
    <div class="container">
      <h1>Counter App</h1>

      <div class="flex flex-col">
        <h2>Count: ${count}</h2>
        <span class="status">${status}</span>
      </div>

      <div class="btn-grp">
        <button onclick="${decrement}">-</button>
        <button onclick="${reset}">Reset</button>
        <button onclick="${increment}">+</button>
      </div>
    </div>
  `;
}

Step 4: Mount the App

/* main.ts */
import App from "./App";
import "./styles.css";

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

What You've Built

This counter app demonstrates:

  • State management with signals using createSignal

  • Event handling with button clicks

  • Computed values that automatically update based on state changes

  • Reactive templates that update the DOM automatically

  • Function-based components for clean code organization

The app is fully reactive - When you click the buttons, the counter value and status message update automatically without any manual DOM manipulation.

Key Concepts Demonstrated

  1. Signals: count stores the current value and notifies when it changes

  2. Computed Values: status automatically recalculates when count changes

  3. Event Handlers: Functions that modify state in response to user interactions

  4. Template Binding: The html template automatically updates when signals change

Last updated