Search code examples
typescriptdomvirtual-domhyperhtml

Detect when component is un/attached to the DOM


I'm moving from React to hyperHTML because performance matters. I'm using third-party libraries specifically for dock panel management from PhosphorJS. When I create this 'DockPanel' class I need to attach it to the real DOM tree.

In React this is can be solved with the function componentDidMount (called right after the virtual nodes are attached to the DOM tree).

So my question, Is there a way to detect when a component is "mounted" and "umounted"? I saw that HyperElement has the dis/connectedCallback function but in the hyper.Components doesn't work.

Thanks!


Solution

  • The hyperHTML.Component has both onconnected and ondisconnected mechanism, as described in the documentation.

    class Clock extends hyper.Component {
      get defaultState() { return {date: new Date()}; }
      onconnected() {
        console.log('finally live');
      }
      render() {
        return this.html`
          <div onconnected=${this} >
            <h1>Hello, world!</h1>
            <h2>It is ${
              this.state.date.toLocaleTimeString()
            }.</h2>
          </div>`;
      }
    }
    

    I'm not familiar with PhosphorJS (first time I heard of it) but if it's based on regular DOM nodes you should be fine.