Components

by mithril

Level: beginner • Mithril.js Version: latest

This is an example of a very simple Mithril.js component, which is just an object with a view function. To activate the component, we have to use m.mount. The example was taken from the official website at https://mithril.js.org/index.html#components.

Live Example

Dependencies

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

HTML

<!doctype html>
<html lang=en>
<head>
  <meta charset=utf-8>
  <title>Components</title>
</head>
<body>
</body>
</html>

JavaScript

let root = document.body
let count = 0 // added a variable

let Hello = {
  view: function() {
    return m("main", [
      m("h1", {
        class: "title"
      }, "My first app"),
      m("button", {
        onclick: function() {count++}
      }, count + " clicks")
    ])
  }
}

m.mount(root, Hello)

The snippet is using the most current version of Mithril.js framework. It is aimed at beginners and shows some basic recipes.

In addition to the Mithril.js hyperscript function m(), here we can see an example of Mithril.js' m.mount API method.

The example was contributed by mithril and last modified on 16 October 2021. Click here to see more examples contributed by the author.

Contribute

If anyone has some improvements, that should be addressed, let me know by opening an issue. Or simply fork the repository on GitHub, push your commits and send a pull request. For starting your work, you can click the edit link below. Thanks for contributing.

See more code examples  •  Edit this example on GitHub