Getting Started With MithrilJS: Set up and DOM Elements

Daniel Patnode
3 min readDec 17, 2020

--

Why Mithril?
With the amount of Javascript frameworks available choosing one that best fits your preferences and ease of use out of the box makes for a real difficult decision. Do you go with the tried and true React, ever changing and widely supported? Ember, for its enhanced handling of complex user interfaces? Angular for the amount of open-source material, power and efficiency? Or Mithril, which boasts a stripped down and dirty framework that gets back to its Javascript roots. Offering straightforward implementation, small size, high speeds and routing, Mithril bundles much of the capabilities of React in a smaller, faster and easy to consume package. In this Article I will go over the set up and how to render basic content to the browser using Mithril.

Comparison of Mithril to other popular frameworks.

The set up
Getting started is relatively simple. To set it up using a CDN (content delivery network) simply create a index.html file containing the following code:

and a related index.js file that will be used to render content:

m.render(document.body, "We just rendered something using Mithril");

and in your terminal run:

open index.html
what we just rendered.

Changing DOM elements
Updating is pretty straight forward as well, using the m() function formatting that was used in index.js, you can assign html structure to the elements like so:

index.js
m.render(document.body, m("h1", "We just rendered something using Mithril"));
what was rendered as a <h1>

classes can also be assigned in much the same way for ease of styling in the future like so:

m.render(document.body, m("h1", { class: "title" }, "We just rendered something using Mithril with a class of 'title' "));
Rendered <h1> with a class of title

These same principals can be applied to rendering buttons, forms, links etc.:

m("main", [
m("h1", {class: "title"}, "Check out this button"),
m("button", "A button"),
])
button and a <h1>

and much more!

This is obviously only the tip of the iceberg. In future blog posts I will go over setting up and implementing JSX syntax, components, routing, XHR requests and project build outs. One final thing, while trying to flush out the syntax for rendering DOM elements in Mithril I came across this super helpful tool that allows you to input normal html and it converts it into Mithrilic syntax, I found it super helpful and really cool! check it out here.

Thanks for reading, if theres anything I missed or you think I should add feel free to leave a comment below.

--

--