Modal with External State

by osban

Level: beginner • Mithril.js Version: latest

In this example we see a Modal component using state that is handled outside the component. So, the message is managed in an simple external state object and injected into the modal within the onclick handler.

Live Example

Dependencies

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

JavaScript

let state = {
  modal: null
}

const Modal = {
  view: () =>
    m('div.modal',
      m('div.c1',
        m('div.c2', state.modal.text),
        m('button', {onclick: () => state.modal = null}, 'OK')
      )
    )
}

const App = {
  view: () => [
    m('h1', 'TEST'),
    m('button', {onclick: () => state.modal = {text: 'This is a modal'}}, 'show modal'),
    state.modal && m(Modal)
  ]
}

m.mount(document.body, App)

CSS

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0,0,0,0.8);
  display: flex;
  justify-content: center;
  align-items: center;
}

.c1 {
  text-align: center;
  padding-bottom: 40px;
  width: 200px;
  height: 100px;
  background: white
}

.c2 {
  padding-top: 40px;
  margin-bottom: 20px
}

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().

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