Tweeter Box

by tbreuss

Level: beginner • Mithril.js Version: latest

This Mithril.js example is a small nonsense Tweeter Box using Mitosis for state management. It shows a textarea HTML element with a counter starting at 140, that is counted down with every char entered. The example is inspired by Jorge Bucaran's Tweeter Box, who wrote it as an example for Hyperapp.

Live Example

Dependencies

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

Markup

<main id="app"></main>

JavaScript

const MAX_LENGTH = 140

const State = () => ({
  message: '',
  charsLeft: MAX_LENGTH
})

const Actions = state => ({
  update: (text) => {
    state.message = text.substr(0, MAX_LENGTH)
    state.charsLeft = MAX_LENGTH - state.message.length
  },
  reset: () => {
    state.message = ''
    state.charsLeft = MAX_LENGTH
  }
})

const TweeterBox = (state, actions) => [
  m('h1', 'Tweeter 🐤'),
  m('textarea', {
    placeholder: 'What\'s on your mind?',
    rows: 4,
    value: state.message,
    oninput: (e) => actions.update(e.target.value)
  }),
  m('section', [
    state.charsLeft,
    m('button', {
      disabled: state.charsLeft === MAX_LENGTH,
      onclick: actions.reset
    }, 'Tweet')
  ])
]

m.mount(document.getElementById('app'), () => {
  const state = State()
  const actions = Actions(state)
  return {
    view: () => TweeterBox(state, actions)
  }
})

Styles

@import "https://unpkg.com/water.css@2/out/water.min.css";

body {
  display: flex;
  font-size: 1.5em;
  justify-content: center;
}

main {
  width: clamp(45ch, 50%, 75ch);
  display: flex;
  flex-direction: column;
}

textarea {
	transition: .2s;
  resize: none;
  overflow: hidden;
}

section {
  display: flex;
}

button {
  margin: 0 0 0 auto;
}

The snippet is using the most current version of Mithril.js framework. It is aimed at beginners and shows some basic recipes.

In addition to the Mithril.js hyperscript function m(), here we can see an example of Mithril.js' m.mount API method.

The example was contributed by tbreuss and last modified on 01 November 2021. Click here to see more examples contributed by the author.

Contribute

If anyone has some improvements, that should be addressed, let me know by opening an issue. Or simply fork the repository on GitHub, push your commits and send a pull request. For starting your work, you can click the edit link below. Thanks for contributing.

See more code examples  •  Edit this example on GitHub