Generic Button Component

by osban

Level: beginner • Mithril.js Version: latest

This is an example showing a generic button component, that can be used to render buttons in different types, colors, floats, and more. It shows also, that implementing a custom compononent in Mithril.js is really simple.

Live Example


Type Name URL


const Button = {
  view: ({attrs: {type, text, onclick, color, disabled, left}}) =>
    m('button', {
      class: color || 'grey',
      type:  type  || 'button',
      style: 'float: ' + (left ? 'none' : 'right')
    }, text)

const app = {
  view: () =>
      m(Button, {text: 'bye',   color: 'blue', left: true}),
      m(Button, {text: 'hello', color: 'red',  left: true, onclick: () => p('click!')}),
      m(Button, {text: 'error', color: 'green'}),
      m(Button, {text: 'test'})

m.mount(document.body, app)


button {
   height: 36px;
   margin-left: 10px;
   padding: 0 16px;
   border: 0;
   border-radius: 4px;
   text-transform: uppercase;
   font-weight: 500px;
   font-size: 14px;
   min-width: 64dp;
   cursor: pointer;
   outline: none

.grey {
  background-color: #f1f1f1;
  color: #616161

.grey:hover {
  background-color: #ccc

.blue {
  background-color: #349cfb;
  color: #fff

.blue:hover {
  background-color: #2c83d4

.red {
  background-color: #eb2024;
  color: #fff

.red:hover {
  background-color: #b6191c

.green {
  background-color: #33b679;
  color: #fff

.green:hover {
  background-color: #2a9928

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.


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