virtual-widget

Create a virtual-dom widget

Usage no npm install needed!

<script type="module">
  import virtualWidget from 'https://cdn.skypack.dev/virtual-widget';
</script>

README

virtual-widget

NPM version build status Test coverage Downloads js-standard-style

Create a virtual-dom widget.

Installation

$ npm install virtual-widget

Usage

// map.js
const virtualWidget = require('virtual-widget')

module.exports = virtualWidget({
  init: function (state) {
    this.state = state
    var elem = document.createElement('div')
    this.map = GoogleMap(elem)
    this.map.setPosition(this.state.position)
    return elem
  },
  update: function (prev, el) {
    this.map = this.map || prev.map
    this.map.setPosition(this.state.position)
  },
  destroy: function (el) {
    // clear position
    this.state.position.set({ x: 0, y: 0 })
  }
})
// view.js
const map = require('./map')

module.exports = view

function view (h, state) {
  return h('section.foo', [
    map(state)
  ])
}

API

render = virtualWidget(hooks)

Create a new virtual-widget using hooks. The following hooks are available:

  • init: run when the element is first created. Define the instantiation logic here.
  • update: run on a re-render. Gives a chance to update state.
  • destroy: run before the widget is unmounted. It is passed the HTMLElement associated with the widget that will be removed. Generally used to clean up data and remove hooks.
  • render: return a string of HTML for server side rendering. It's recommended to use vdom-to-html for server-side rendering.

See Also

License

MIT