atomicojs / atomico

Atomico a micro-library for creating webcomponents using only functions, hooks and virtual-dom.
https://atomicojs.dev
MIT License
1.16k stars 43 forks source link

How do I get a reference to the custom element node? #48

Closed leifriksheim closed 3 years ago

leifriksheim commented 3 years ago

I have some code like this. How do I get a reference to the custom element node itself?

  useEffect(() => {
    document.querySelector(selector).addEventListener(event, openMenu);
    window.addEventListener("click", (e) => {
      const clickedInside = refToCustomElementNode.contains(e.target);
      if (!clickedInside) {
        this.open = false;
      }
    });
  }, []);

I tried using a ref on the host like this <host ref=${ref}> but it didn't work. Couldn't seem to find anything about this in the docs.

UpperCod commented 3 years ago

Hi, There are 2 ways to retrieve the customElement instance, useHost and useRef, example

useHost, useHost is a powerful tool since it allows you to access the webcomponent instance without having to reference in the host tag, example livecode

import { c, useHost, useEffect } from "atomico";
import html from "atomico/html";

/**
 * useHost is a powerful tool since it allows
 * you to access the webcomponent instance
 * without having to reference in the host tag
 */
function useMyCustomHook() {
  const ref = useHost();
  useEffect(() => {
    const { current } = ref;
    current.style.fontSize = "30px";
    current.style.color = "crimson";
  }, []);
}

function example() {
  useMyCustomHook();
  return html`<host shadowDom>example...</host>`;
}

customElements.define("my-example", c(example));

useRef, This hook is homologous to React, example livecode

import { c, useRef, useEffect } from "atomico";
import html from "atomico/html";

function example() {
  const ref = useRef();

  useEffect(() => {
    const { current } = ref;
    current.style.fontSize = "30px";
    current.style.color = "crimson";
  }, []);

  return html`<host shadowDom ref=${ref}>example...</host>`;
}

customElements.define("my-example", c(example));

I tried using a ref on the host like this <host ref=${ref}> but it didn't work.

Please can you refer me to the code to verify the bug, since the comments should work, This would be an example of the bug?

How is the code of refToCustomElementNode?