Force Component Re-Init without Routing

by osban

Level: beginner • Mithril.js Version: latest

This is an example that forces a component to re-initialize by using a key attribute.

Keys are used usually to distinguish similar vnodes from one another. However, due to how Mithril.js treats keyed vnodes, we can use keys to force a vnode to be re-created. This could be useful for situations wherein we want to, say, modify attributes of a 3rd-party component that doesn't provide an API to do so - we could simply force the component to be re-created with new values.

In this example we create 2 instances of component, but assign a key only to the 'foo' instance; note that the value of the assigned key changes every time. Thus, on a redraw, when Mithril.js doesn't find a new vnode with the old key, it discards the old vnode, and creates a new one with the new key, and new values.

Keep in mind that every sibling needs a key, otherwise it doesn't work.

Live Example

Dependencies

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

JavaScript

const component = {
  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(component, {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 16 October 2021. 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