Can I use HyperX with Snabbdom

294 Views Asked by At

HyperX is a module that translates a tagged template literal to a hyperscript function like the one included with virtual-dom.

Snabbdom uses a hyperscript-like function to build it's vdoms, but it's second argument is different. Instead of attributes it's properties are used by various "modules";

h('div', {
  props: {title: someString}, // snabbdom/modules/props
  classes: {selected: isSelected}, // snabbdom/modules/class
  on: {click: doSomething}, // snabbdom/modules/eventlisteners
  style: {color: someColor} // snabbdom/modules/style
}, ['children']);

Is it possible to use hyperx with snabbdom's hyperscript function like so:

const h = require('snabbdom/h');
const hyperx = require('hyperx');
const hx = hyperx(h);

let vdom = hx`
  <div 
    title=${someString} 
    class-selected={isSelected} 
    on-click={doSomething} 
    style={({color: someColor})}
  >
   children
  </div>
`;
1

There are 1 best solutions below

2
On

Yes you can!

var snabbdom = require('snabbdom')
var patch = snabbdom.init([ // Init patch function with chosen modules
  require('snabbdom/modules/class'), // makes it easy to toggle classes
  require('snabbdom/modules/props'), // for setting properties on DOM elements
  require('snabbdom/modules/style') // handles styling on elements with support for animations  
])
var h = require('snabbdom/h')
var hyperx = require('hyperx')
var hx = hyperx(h)

var title = 'world'
var wow = [1,2,3]
var tree = hx`<div>
  <h1 y="ab${1+2}cd">hello ${title}!</h1>
  ${hx`<i>cool</i>`}
  wow
  ${wow.map(function (w, i) {
    return hx`<b>${w}</b>\n`
  })}
</div>` 
patch(document.body, tree)

check the working code here