Categories
Tutorials

Get Started with Mithril

This will be the first of many tutorials covering the lesser known but very powerful and performant javascript framework Mithril.js. Mithril is primarily used for SPA (Single Paged Applications) but also works well as a drop in for existing sites and in many cases a replacement for jQuery.

Creating a basic HTML file

Start by creating a basic html file like the example below:

<!DOCTYPE HTML>
<html>
	<head>
		<title>Get Started with Mithril</title>
	</head>
	<body></body>
</html>

Importing Mithril

The Mithril library can be added via module or CDN. For this example add Mithril via CDN:

<!DOCTYPE HTML>
<html>
	<head>
		<title>Get Started with Mithril</title>
	</head>
	<body>
        <script src="https://unpkg.com/mithril/mithril.js"></script>
    </body>
</html>

Attaching to DOM

The “m” object becomes available after importing mithril.js. Use console.log(m) for further inspection. The m.render function will be used to render “Hello World”, taking a DOM element as the first parameter the a string or function as the second parameter. In this instance, the body will be used for the DOM and “Hello World” as the string.

<!DOCTYPE HTML>
<html>
	<head>
		<title>Get Started with Mithril</title>
	</head>
	<body>
        <script src="https://unpkg.com/mithril/mithril.js"></script>
		<script>
			const root = document.body;
			m.render(root, "Hello world");
		</script>
    </body>
</html>

Rendering DOM elements with “m(“

It was mentioned earlier that m.render also accepts a function, specifically the “m(” function as a parameter. The following renders an H1 element in place of a string:

<!DOCTYPE HTML>
<html>
	<head>
		<title>Get Started with Mithril</title>
	</head>
	<body>
        <script src="https://unpkg.com/mithril/mithril.js"></script>
		<script>
			const root = document.body;
			m.render(root, m('h1', "Hello world") );
		</script>
    </body>
</html>

Element attributes can also be added as needed:

<!DOCTYPE HTML>
<html>
	<head>
		<title>Get Started with Mithril</title>
	</head>
	<body>
        <script src="https://unpkg.com/mithril/mithril.js"></script>
		<script>
			const root = document.body;
			m.render(root, m('h1', { class: 'entry-header', style: 'color:red;' },"Hello world") );
		</script>
    </body>
</html>

Multiple elements can be rendered by adding them to an array:

<!DOCTYPE HTML>
<html>
	<head>
		<title>Get Started with Mithril</title>
	</head>
	<body>
        <script src="https://unpkg.com/mithril/mithril.js"></script>
		<script>
			const root = document.body;
			m.render(root, [
				m('h1', { class: 'entry-header', style: 'color:red;' },"Hello world"),
				m('p','Lorem Ipsum...')
			]);
		</script>
    </body>
</html>

The next tutorial will explain the differences between m.mount and m.render.

An Introduction to Mithril Components →

Leave a Reply

Your email address will not be published. Required fields are marked *