Level: beginner • Mithril.js Version: latest
dom m.mount oncreate react vnode
This example shows how to access dom nodes of a component, much like Reacts refs.
Type | Name | URL |
---|---|---|
script | mithril@latest | https://unpkg.com/mithril@latest |
function findRef(dom, ref) {
return dom.matches(`[ref=${ref}]`) ? dom : dom.querySelector(`[ref=${ref}]`)
}
const MyComponent = {
oncreate(vnode) {
const title = findRef(vnode.dom, 'title')
title.style.color = 'red'
},
view() {
return m('h1', { ref: 'title' }, 'abc')
}
}
m.mount(document.body, MyComponent)
The snippet is using the most current version of Mithril.js framework. It is aimed at beginners and shows some basic recipes.
In addition to the Mithril.js hyperscript function m(), here we can see an example of Mithril.js' m.mount
API method.
It also shows, how Mithril.js' lifecycle methods can be used. This can be seen here by using the oncreate
hook.
In this example we can also see the usecase of Vnodes (virtual DOM nodes) which is a JavaScript data structure that describes a DOM tree.
The example was contributed by stephanhoyer and last modified on 26 October 2021. Click here to see more examples contributed by the author.
If anyone has some improvements, that should be addressed, let me know by opening an issue. Or simply fork the repository on GitHub, push your commits and send a pull request. For starting your work, you can click the edit link below. Thanks for contributing.