Counter

The smallest complete Reactive program, built from the UI abstraction: a row with two buttons that step a piece of state up and down, and its value shown between them. The buttons bind straight to the state.

Live

This is running the real framework, on this page: the four scripts in the head and the code below.

Press the buttons; the number is reactive state.

The code

Reactive.Mount(() => {
  const ui = Dom(() => {
    const count = Reactive.State(Maths.Integer)(0);

    Layout.Row(() => {
      Button.Integer.Decrement(count, () => {
        Content.Text("decrement");
      });
      Content.Text(count);
      Button.Integer.Increment(count, () => {
        Content.Text("increment");
      });
    });
  });
  return { content: ui.content };
}, { content: { root: document.getElementById("counter") } });
Two buttons step the count up and down, with its value between them.

What happens

Reactive.State(Maths.Integer)(0) declares one piece of reactive state. Layout.Row arranges its three children in a row, and each child is a component bound straight to count.

Button.Integer.Decrement and Button.Integer.Increment each name the state they change and the step to take; pressing one moves count by one. Content.Text shows the current value, and each button's label is the Content.Text in its closure.

Any change re-runs the whole program, and the driver patches just the number that moved. Keeping the display in step with the state falls out of the update loop.

Tasks → Back to examples