Level: intermediate • Mithril.js Version: latest
In Mithril.js you are free to structure your state data however you'd like, and Mithril.js takes care of the rest. Below is a versatile state container using plain JavaScript objects for state and actions.
Type | Name | URL |
---|---|---|
script | mithril@latest | https://unpkg.com/mithril@latest |
const state = { count: 0 };
const actions = {
increment: () => state.count += 1,
decrement: () => state.count -= 1
};
const Counter = {
view: () =>
m('div',
m('h1', 'Counter'),
m('p', state.count),
m('button', { onclick: actions.increment }, '+'),
m('button', { onclick: actions.decrement }, '-')
)
};
m.mount(document.body, Counter);
With the above solution we are not modifying the state directly from within the view. This way the Counter component becomes more terse, yet more expressive.
As a prerequisite for this snippet, the latest version of Mithril.js framework is required. The example targets intermediate users, that are familiar with with most aspects of the framework.
In this code sample Mithril.js' m.mount
API method is use, besides the basic hyperscript function m().
The example was written by kevinfiol, last edits were made on 19 October 2021. The author has contributed some more snippets. Click here to see them all.
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!