Re-initializing a Component Using Key - Without Routing

by osban

Level: beginner • Mithril.js Version: latest

To distinguish similar vnodes from eachother, use the KEY attribute (keyword), and give it a unique value. Keep in mind that all siblings must be keyed for it to work. See also the Mithril.js docs. This can be used to force a component to re-instantiate/re-initialize. In this example 2 comp instances are created, but only the 'foo' one gets a changeable key, ensuring the re-init when the key changes.

Live Example

Dependencies

Type Name URL
scriptmithril@latesthttps://unpkg.com/mithril@latest

JavaScript

const comp = {
  oninit: vnode => console.log('init ' + vnode.attrs.name),
  view: vnode => m('div', vnode.attrs.name + ' key: ' + vnode.attrs.key)
}

const app = () => {
  count = 0

  return {
    oninit: () => {console.log('init app')},
    view: () => [
      m('div', 'Test',
        ['foo','bar'].map(x => m(comp, {name: x, key: x === 'foo' && count}))
      ),
      m('button', {onclick: () => count++}, 'click')
    ]
  }
}

m.mount(document.body, app)

As a prerequisite for this snippet, the latest version of Mithril.js framework is required. Beginners should have no problems following this example, that simply shows some basic recipies.

In this code sample Mithril.js' m.mount API method is use, besides the basic hyperscript function m(). Moreover, it shows how the lifecycle method oninit can be used (better known as hook). Also covered in this example is the use of Vnodes or virtual DOM nodes, a JavaScript data structure that describes a DOM tree.

The example was written by osban, last edits were made on 24 September 2020. The author has contributed some more snippets. Click here to see them all.

Contribute

Did you note a typo or something else? So let me know by opening an issue. Or much better: just fork the repository on GitHub, push your commits and send a pull request. Ready to start your work? Then click on the edit link below. Thanks in advance!

See more code examples  •  Edit this example on GitHub