MithrilJS / mithril.js

A JavaScript Framework for Building Brilliant Applications
https://mithril.js.org
MIT License
13.98k stars 925 forks source link

htm with Mithril.js #2899

Closed michaelsboost closed 1 month ago

michaelsboost commented 1 month ago

I know I can use htm with Hyperapp like this...

import { app } from 'https://unpkg.com/hyperapp';
import html from 'https://unpkg.com/hyperlit';

app({
  init: 0,
  view: count => html`
    <div class="flex flex-col items-center justify-center absolute inset-0">
      <h1 class="text-3xl font-thin mb-4">👋 Hello, Hyperapp! 🌎</h1>
      <p class="text-xl mb-4">Counter: <span class="font-mono">${count}</span></p>
      <button onclick=${count => count + 1}>+</button>
    </div>`,
  node: document.getElementById('root')
})

I know I can use htm with Preact like this...

/** @jsx h */
import { html, render, useState, useEffect } from 'https://unpkg.com/htm@3.1.1/preact/standalone.module.js';

function App() {
  const [counter, setCounter] = useState(0);

  return html`
    <div class="flex flex-col items-center justify-center absolute inset-0">
      <h1 class="text-3xl font-thin mb-4">👋 Hello, Preact! 🌎</h1>
      <p class="text-xl mb-4">Counter: <span id="counter" class="font-mono">${counter}</span></p>
      <button
        id="incrementButton"
        class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-700 transition"
        onClick=${() => setCounter(counter + 1)}
      >
        +
      </button>
    </div>
  `;
}

render(html`<${App} />`, document.getElementById('root'));

I can go on with various examples. Can I do the same with Mithril.js?

dead-claudia commented 1 month ago

Should be as simple as const html = htm.bind(m);.

An integration with Mithril would look almost identical to their React integration:

import m from 'mithril'
import htm from 'htm'
export const html = htm.bind(m)
osban commented 1 month ago

Here's a code example of that: example.

michaelsboost commented 1 month ago

Thanks got it to work

import htm from 'https://unpkg.com/htm?module'
const html = htm.bind(m)

const app = () => {
  let count = 0

  return {
    view: () => html`
      <div class="flex flex-col items-center justify-center absolute inset-0">
        <h1 class="text-3xl font-thin mb-4">👋 Hello, Mithril! 🌎</h1>
        <p class="text-xl mb-4">Counter: <span class="font-mono">${count}</span></p>
        <button onclick=${() => count++}>+</button>
      </div>`
  }
}

m.mount(document.getElementById('root'), app)