Component Class Counter

by osban

Level: beginner • Mithril.js Version: latest

This is another example showing a very simple Component class. It is one of the classic examples, that shows a counter, that can be increased or decreased by clicking one of two appropriate buttons. Using classes isn't really recommended, but of course if you have to, it will work just fine with Mithril.js.

Live Example

Dependencies

Type Name URL
scriptmithril@latesthttps://unpkg.com/mithril@latest

JavaScript

class app {
  constructor() {
    this.count = 0
  }

  view() {
    return [
      m('div',
        m('h1', `Count: ${this.count}`),
        m('button', {onclick: () => this.count++}, '+'),
        m('button', {onclick: () => this.count--}, "-")
      )
    ]
  }
}

m.mount(document.body, app)

As a prerequisite for this snippet, the latest version of Mithril.js framework is required. Beginners should have no problems following this example, that simply shows some basic recipies.

In this code sample Mithril.js' m.mount API method is use, besides the basic hyperscript function m().

The example was written by osban, last edits were made on 24 September 2020. The author has contributed some more snippets. Click here to see them all.

Contribute

Did you note a typo or something else? So let me know by opening an issue. Or much better: just fork the repository on GitHub, push your commits and send a pull request. Ready to start your work? Then click on the edit link below. Thanks in advance!

See more code examples  •  Edit this example on GitHub