Skip to main content

Overview

The Counter example is a minimal app that demonstrates the fundamentals of GlyphUI:
  • Component-based architecture
  • Local state management with setState
  • Event handling with the on property
  • Virtual DOM rendering with h() and hFragment()

Live Demo

View the complete source code on GitHub

What You’ll Learn

Component Class

Extending the base Component class

State Management

Using setState to update component state

Event Handling

Binding click events to methods

Virtual DOM

Creating elements with h() function

Complete Code

Component Implementation

counter.js
import {
  Component,
  h,
  hFragment,
  hString,
} from "@glyphui/runtime";

class CounterApp extends Component {
  constructor() {
    super({}, {
      initialState: { count: 0 }
    });
  }
  
  increment() {
    this.setState({ count: this.state.count + 1 });
  }
  
  decrement() {
    this.setState({ count: this.state.count - 1 });
  }
  
  render(props, state) {
    return hFragment([
      h("button", { on: { click: () => this.decrement() } }, ["-"]),
      h("span", {}, [
        hString("count is: "),
        hString(state.count),
      ]),
      h("button", { on: { click: () => this.increment() } }, ["+"]),
    ]);
  }
}

// Mount the app
const app = new CounterApp();
app.mount(document.querySelector("main"));

Key Concepts

1. Component Constructor

The constructor initializes the component with an initial state:
constructor() {
  super({}, {
    initialState: { count: 0 }
  });
}
  • First argument {} is for props (empty in this case)
  • Second argument defines the initial state

2. State Updates

The setState() method triggers a re-render:
increment() {
  this.setState({ count: this.state.count + 1 });
}
setState() merges the new state with the existing state and automatically triggers a re-render.

3. Event Handling

Events are bound using the on property:
h("button", { on: { click: () => this.increment() } }, ["+"])
The on object maps event names to handler functions.

4. Virtual DOM Creation

Elements are created using helper functions:
  • h(tag, props, children) - Creates a virtual DOM element
  • hFragment(children) - Groups multiple elements without a wrapper
  • hString(text) - Creates a text node

Running the Example

1

Clone the repository

git clone https://github.com/x0bd/glyphui.git
cd glyphui/examples/counter
2

Install dependencies

npm install
3

Open in browser

Open counter.html in your browser or use a local development server:
npx serve .

Next Steps

Todo App

Learn about global state management with stores

Components Guide

Deep dive into component architecture

State Management

Learn more about managing state

Event Handling

Master event handling patterns

Build docs developers (and LLMs) love