Skip to content

fuzetsu/microh

Repository files navigation

microh npm npm bundle size

A small and simple hyperscript wrapper for vdom libraries such as (but not limited to) Preact, React, and Hyperapp.

Features

  • optional attrs h('h1', 'Hello World')
  • inline classNames h('button.button.is-primary')
  • no tag name means div h('.login-area')
  • varargs h('div', 'Hello', 'World', 'the time is', Date.now())
import { h, render } from 'preact'
import microh from 'microh'

// create a wrapped instance of h by passing it to microh
const m = microh(h)

const vnode = m(
  'ul.list',
  m('li.list-item', 'one'),
  m('li.list-item', 'two'),
  m('li.list-item', 'three')
)

render(vnode, document.body)

playground

Installation

esm modules

import microh from 'https://unpkg.com/microh?module'

Browser

<script src="https://unpkg.com/microh"></script>
<script>
  window.microh
</script>

NodeJS

// npm install microh
const microh = require('microh')

Usage

React

import React from 'react'
import microh from 'microh'

const m = microh(React.createElement)

Preact

import { h } from 'preact'
import microh from 'microh'

const m = microh(h)

Hyperapp

For hyperapp 2.0.4 and earlier microh will work out of the box:

import { h } from 'hyperapp'
import microh from 'microh'

const m = microh(h)

For later versions you will have to use this snippet because of changes to how vNodes are structured and how text children are handled:

import { h, text } from 'hyperapp'
import microh from 'microh'

const m = microh((tag, props, ...children) =>
  typeof tag === 'function'
    ? tag(props, children)
    : h(
        tag,
        props,
        []
          .concat(...children)
          .map(child =>
            typeof child === 'string' || typeof child === 'number' ? text(child) : child
          )
      )
)

If you don't use this custom function microh will still work but you will have to wrap text in text() calls yourself and call components as functions directly.

Other Libraries

If you're using another vdom library and directly passing the equivalent of the h() function to microh doesn't work you can always pass a function that calls the h() with any necessary adjustments made.

For example, say a particular vdom library always expects children to be passed as an array, you could handle it like this:

import { makeElem } from 'some-vdom'
import microh from 'microh'

const m = microh((tag, props, ...children) => makeElem(tag, props, children))