DEV Community

Adrián Bailador
Adrián Bailador

Posted on

Mithril.js: A Modern Framework for JavaScript

What is Mithril.js?

Mithril.js is a modern client-side JavaScript framework for building Single Page Applications (SPAs). It is small (less than 10kb gzip), fast, and provides routing and XHR utilities out of the box. Mithril.js is used by companies like Vimeo and Nike, as well as open-source platforms like Lichess.

Comparison with other frameworks

Mithril.js shares many similarities with React. Both use virtual DOM, lifecycle methods, and key-based reconciliation. However, React is a view library, so a typical React-based application relies on third-party libraries for routing, XHR, and state management. Mithril.js, on the other hand, has built-in modules for common needs like routing and XHR.

In terms of size, Mithril.js is much smaller and faster compared to popular frameworks like React and Angular.

Creating a component

A component in Mithril.js is simply an object with a view function. Here's an example of what a component looks like in Mithril.js:

var Hello = {
    view: function() {
        return m("main", [
            m("h1", {class: "title"}, "My first application"),
            m("button", "A button"),
        ])
    }
}

m.mount(root, Hello)
Enter fullscreen mode Exit fullscreen mode

This code creates a Hello component that displays a title and a button on the page.

Advantages of Mithril.js

  • Small size: Mithril.js is one of the smallest JavaScript frameworks available, with a size of only 8KB.
  • Easy to learn: Mithril.js has a simple and intuitive API that is easy to learn, even for developers who are new to JavaScript frameworks.
  • Fast performance: Mithril.js is designed to be fast and efficient, with minimal overhead and fast rendering times.
  • No build stage required: Many web pages today are not single-page applications built with Webpack.
  • Community support: Although Mithril.js has a smaller community compared to other more popular frameworks, its community is very active and offers great support.

Disadvantages of Mithril.js

  • Smaller community and limited resources: Compared to more adopted frameworks, Mithril.js has a smaller community. This may result in fewer online resources, tutorials, and community support options.
  • Less mature ecosystem: Although Mithril.js has an active community, the ecosystem around it is relatively smaller compared to other frameworks.

Routing in Mithril.js

Routing is a system that allows creating Single Page Applications (SPAs), i.e., applications that can transition from one page to another without causing a full browser refresh. Mithril.js provides a routing API that allows applications to respond to changes in the URL.

Here's an example of how routing is set up in Mithril.js:

var Home = {
    view: function() {
        return "Welcome Codú"
    }
}

m.route(document.body, "/home", {
    "/home": Home,
})
Enter fullscreen mode Exit fullscreen mode

In this code, m.route is used to set up routing. The first argument is the DOM element where the application will be mounted, the second argument is the default route, and the third argument is an object that maps routes to components.

XHR in Mithril.js

XHR (XMLHttpRequest) is a method for communicating with the server. Mithril.js provides its own implementation (m.request) that facilitates XHR requests and redraws the UI after each XHR request.

Here's an example of how an XHR request is made in Mithril.js:

m.request({
    method: "GET",
    url: "https://pokeapi.co/api/v2/pokemon?limit=100000&offset=0"
})
.then(function(result) {
    console.log(result);
})
Enter fullscreen mode Exit fullscreen mode

In this code, m.request is used to make a GET request to the server. The method returns a promise that resolves with the result of the request.

Handling route parameters

Mithril.js allows handling route parameters. Route parameters are key-value pairs that can come from route interpolations (e.g., if a route is /users/:id, and resolves to /users/1, the route parameter has a key id and a value "1"), router query strings (e.g., if the route is /users?page=1), and the state object passed to the underlying history.pushState / history.replaceState call.

Here's an example of how route parameters are handled in Mithril.js:

var Article = {
    view: function(vnode) {
        return "This is article " + vnode.attrs.articleid
    }
}

m.route(document.body, {
    '/article/:articleid': Article
})

m.route.set('/article/:articleid', {articleid: 1})
Enter fullscreen mode Exit fullscreen mode

In this code, m.route.set is used to set the route to /article/:articleid, where :articleid is a route parameter interpolated with the value of articleid in the parameters object.

Lifecycle methods

Components and virtual DOM nodes in Mithril.js can have lifecycle methods, also known as hooks, which are called at various points during the life of a DOM element. Lifecycle methods receive the vnode as their first argument, and have their this keyword bound to vnode.state.

The lifecycle of a DOM element typically includes creation and attachment of the element to the document, updating attributes or child nodes when a UI event is triggered and data changes, and removal of the element from the document.

Here's an example of how lifecycle methods are used in Mithril.js:

var ComponentWithHooks = {
    oninit: function(vnode) {
        console.log("initialized")
    },
    oncreate: function(vnode) {
        console.log("DOM created")
    },
    onbeforeupdate: function(newVnode, oldVnode) {
        return true
    },
    onupdate: function(vnode) {
        console.log("DOM updated")
    },
    onbeforeremove: function(vnode) {
        console.log("exit animation can start")
        return new Promise(function(resolve) {
            // call after animation completes
            resolve()
        })
    },
    onremove: function(vnode) {
        console.log("removing DOM element")
    },
    view: function(vnode) {
        return "hello"
    }
}
Enter fullscreen mode Exit fullscreen mode

In this code, ComponentWithHooks is a component that has several lifecycle methods. Each lifecycle method logs a message to the console when called.

Conclusion

In summary, Mithril.js offers an efficient and lightweight alternative for client-side web development. Its small size, fast performance, and intuitive API make it appealing to both experienced developers and those just starting out in the world of JavaScript frameworks.

Official Website

You can find more information about Mithril.js on its official website.

Top comments (0)