0

When using the virtual-dom library, how can I get hold of the real DOM element corresponding to a virtual one? The use case is I need to manipulate the DOM via the spin.js library.

Correspondingly, in React you would call React.findDOMNode in order to get hold of the element to pass to spin.js.

Example code:

let el = h('#spinner')
# TODO: Pass real DOM element, not virtual, but how?
new Spinner().spin(el)
aknuds1
  • 65,625
  • 67
  • 195
  • 317

1 Answers1

1

I found I could solve this by registering a hook on the virtual node in question, a little documented feature of virtual-dom AFAICT. The hook gets called with the real DOM node once it's rendered.

virtual-dom is very specific about its hooks, they need to be objects with hook and unhook functions on their prototypes (can't be direct properties).

let h = require('mercury').h

// Hook to get hold of real DOM node
let Hook = () => {}
Hook.prototype.hook = (node) => {
  // Do what thou wilst with the node here
}
Hook.prototype.unhook = () => {}

// Mercury component
let Component = () => {
}

Component.render = (state) => {
  // Create virtual node with hook
  return h('div', {
    hook: new Hook(),
  })
}
aknuds1
  • 65,625
  • 67
  • 195
  • 317