Modal with Internal State

by osban

Level: beginner • Mithril.js Version: latest

In this example we see a Modal component using internal state. For the content of the modal we have a Content component, that supports different types of modals like Alert, Confirmation, or others. Type and message attributes are injected into the Modal component, therefore no external state is needed.

Live Example


Type Name URL


const Content = {
  alert: {
    view: ({attrs: {text, click}}) => [
        m('div.c2', text),
        m('button', {onclick: click}, "OK")

const Modal = {
  view: ({attrs: {type, content}}) => [
      m(Content[type], content)

const App = () => {
  let showmodal = false

  return {
    view: () => [
      m('h1', "TEST"),
      m('button', {onclick: () => showmodal = true}, "modal"),
      showmodal &&
      m(Modal, {type: 'alert', content: {text: "This is an alert", click: () => showmodal = false}})

m.mount(document.body, App)


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


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