DEV Community

Cover image for Mithril Hello World Example
Manish Champaneri
Manish Champaneri

Posted on • Originally published at learnit.mchampaneri.in

Mithril Hello World Example

Table of content

# Introduction

Hello world program is best starting point to learn new programming language or framework.

This hello world program will explain how to do very basic minimal setup to use Mithril and then will end with displaying "Hello world" printed on screen.

# Prepare basic HTML

Create html file with the basic tags of html, head, title, and body.

<html>
    <head>
          <title>Mithril Hello World Example</title>
    </head>
    <body>   
   </body>
</html>
# Include Mithril library

We will be using Mithril CDN for our example.

<head>
    <script src="https://unpkg.com/mithril/mithril.js">
    </script>
</head>
# Add mounting element for Mithril in dom and mount Mithril there.

We will be using div element with id app as mounting point of our Mithril app.

<body>
   <div id="app"></div>
</body>

Now we have to inform Mithril, that we want to use the element with id 'app' has to be used as mounting point of Mithril.
In order to do that we have to select that dom element from dom.

 var app = document.getElementById("app") 

After adding mounting point our code will look like.

I am saying it as mounting point because mithril actually mounts dom elements to that dom element as child and you can have multiple mounting points for multiple mithril rendering functions. See example multiple mounting points

<body>
    <div id="app"></div>
    <script type="text/javascript">
          var app = document.getElementById("app")
    </script>
</body>
# Render "Hello world" by Injecting Hello world inside mounting element

We have added Mithril library and also have a mounting point for it. Let's render simple "Hello world" by injecting it inside mounting point.

Here m represents Mithril object.
We are using m.render function for rendering.

<!DOCTYPE html>
<html>
  <head>
    <title>Mithril Hello World Example</title>
    <script src="https://unpkg.com/mithril/mithril.js"></script> 
    </head>
    <body>
      <div id="app"></div>
        <script type="text/javascript">
          var app = document.getElementById("app");
          m.render(app, "Hello world");
        </script>
    </body>
</html>
# Example

Take a look at live example hosted on codesandbox !
Codesandbox Example

Oldest comments (0)