How to reimplement material.io components in hyperHTML?

253 Views Asked by At

I am looking at this React example of how material.io component is implemented/integrated with React component:

https://github.com/material-components/material-components-web/blob/master/framework-examples/react/src/Checkbox.js

I wonder how one would go about doing same with hyperHTML since there are no lifecycle event calls within hyper.Component like componentDidMount or componentWillUnmount.

It was said that I can do that after render call but that is typically called from outside of component.

1

There are 1 best solutions below

0
On BEST ANSWER

sorry I've seen this only now.

I'd like to clarify a couple of things:

there are no lifecycle event calls within hyper.Component like componentDidMount or componentWillUnmount.

If you try latest version, or let's say 1.10+, you will have the ability to define onconnected(evt) { ... } and ondisconnected(evt) { ... } methods in each of your hyper.Component class definition.

It's a fairly recent feature, unfortunately not documented yet. but it provides all you need to behave like Custom Elements connectedCallback and disconnectedCallback methods (and remember, there is also an HyperHTMLElement project to create real custom elements).

The following is a basic example:

import {Component} from 'hyperhtml';

class Clock extends Component {

  update() {
    this.time = (new Date).toLocaleTimeString();
    this.render();
  }

  // equivalent of Custom Elements connectedCallback
  onconnected() {
    console.log('start time');
    this.update();
    this.timer = setInterval(() => this.update(), 1000);
  }

  // equivalent of Custom Elements disconnectedCallback
  ondisconnected() {
    console.log('end time');
    clearInterval(this.timer);
  }

  render() { return this.html`
    <p
      onconnected=${this}
      ondisconnected=${this}
    >
      ${this.time}
    </p>`;
  }
}

I hope this would give you enough power to replicate the material example.


The other part I'd like to clarify:

It was said that I can do that after render call but that is typically called from outside of component.

That's not entirely correct. Yes, the component.render() is called automatically, if needed, but what matters is what you return.

I am using the same code I've used for the previous Clock example:

// same code as before
  render() {
    const p = this.html`
    <p
      onconnected=${this}
      ondisconnected=${this}
    >
      ${this.time}
    </p>`;

    // you have a <p> element here
    // you can do whatever you want
    // example:
    p.addEventListener('click', console.log);

    // now you should return it
    return p;
  }
// rest of the code

as you can see, you can always interact with the rendered node. After all, all hyperHTML does, is creating the content you write, nothing more, nothing less.

I hope these clarifications would help you to move forward. Here, eventually, to answer other questions.