Mithril.js: A Modern Framework for JavaScript
Tags: javascript, webdev, react, programming
Published: 2024-04-25 08:38:46

## 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:

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

m.mount(root, Hello)
```

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:

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

m.route(document.body, "/home", {
    "/home": Home,
})
```

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:

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

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:

```javascript
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})
```

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:

```javascript
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"
    }
}
```

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](https://mithril.js.org/).