home blog portfolio Ian Fisher

Mithril.js cheatsheet

https://mithril.js.org/

import m from "mithril";

const PageView = {
  view() {
    return m(GreetingView, { name: "world" });
  },
};

const GreetingView = {
    view(vnode) {
        const name = vnode.attrs.name;
        return m("p", `Hello, ${name}!`);
    },
};

// or, with classes:

class PageView {
    view() {
        return m(GreetingView, { name: "world" });
    }
}

class GreetingView {
    view(vnode) {
        const name = vnode.attrs.name;
        return m("p", `Hello, ${name}!`);
    }
}

m.mount(document.body, PageView);

Component with state

interface MyViewAttrs {
  x: string;
}

class MyView implements m.Component<MyViewAttrs> {
  private x: string;

  constructor(vnode: m.Vnode<MyViewAttrs>) {
    this.x = vnode.attrs.x;
  }

  view(): m.Children {
    return m("p", `My parameter: ${this.x}`);
  }
}

// or, with constants

const MyView = {
    oninit(vnode) {
        vnode.state.x = 'whatever';
    },
};

Event handlers

m("input", { onkeydown: (e) => this.onKeyDown(e) })

onKeyDown(e) {
  if (e.key === "Enter") {
    // ...
  }
}

API requests

class MyView {
  constructor() {
    this.state = null;
  }

  oninit() {
    m.request({ method: "GET", url: "/api/load" }).then(data => {
      this.state = data;
    });
  }

  myClickHandler() {
    m.request({
      method: "POST",
      url: "/api/submit",
      body: { ... },
      headers: {
        "Content-Type": "application/json",
      },
    });
  }
}

Un-escape HTML output

m.trust("&ndash;")