Categories
Tutorials

An Introduction to Mithril Components

As with other popular frameworks, mithril allows developers to encapsulate functionality into reusable components. A mithril component is comprised of an object containing lifecycle methods and a “view” method to render HTML. vnode(s) are javascript objects that represent the virtual DOM elements.

const componentAnatomy = {
	
    oninit: vnode => {
        console.log("component initialized");
    },
    
    oncreate: vnode => {
        console.log("component DOM created");
    },
    
    onbeforeupdate: => (newVnode, oldVnode) => {
	    console.log("component updated internal state data");
        return true
    },
    
    onupdate: vnode => {
        console.log("component DOM updated");
    },
    
    onbeforeremove: vnode => {
	    
        console.log("exit animation can start");
        
        return new Promise( (resolve) => {
            // call after animation completes
            resolve();
        });
    },
    
    onremove: vnode => {
        console.log("removing DOM element");
    },
    
    view: vnode => {
        return "hello"
    }
};

To create a vnode, an HTML element tag, id, class, or component is passed to the m() hyperscript function…

m('h1','Hello World')

…which is then returned by the view method of the component.

const helloWorld = {
	
	view: vnode => m('h1','Hello World')
};

State, DOM attributes, event handlers and lifecycle methods can also be passed into components via the attrs property of the vnode object.

const helloWorld = {
	
	view: vnode => m('h1',{
		class: 'entry-header',
		style: 'color:blue;',
		onclick: e => {
			console.log( "Do Something")
		}
	},'Hello World')
};

m.render(document.body,helloWorld);

More advanced component implementation and state management will be covered in future tutorials.

Leave a Reply

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