atomicojs / atomico

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

How can I select nodes within shadow DOM? #32

Closed srdjan closed 4 years ago

srdjan commented 4 years ago

tried both: ... document.querySelectorAll('div') and document.querySelectorAll('my-tag::shadow div') ...

but get zero elements back.

full example: https://codepen.io/djidja8/pen/NWGwymZ

Thanks! Lovely project

UpperCod commented 4 years ago

Hi @srdjan, thanks for trying Atomico, to make queries inside the webcomponent you must first create a reference with the hook useRef, this can be assigned to any element of the DOM inside the webcomponent, eg: https://codepen.io/uppercod/pen/BaoJyNK?editors=1010

import { customElement, useEffect, useRef } from "https://unpkg.com/atomico";

function MyTag() {
  let ref = useRef(); // just like the react hook, it will create an object for reference

  useEffect(() => {
    let { current } = ref; // the current property has the reference to the element
    console.log(current.querySelectorAll("div"));
  }, []);

  return html`
    <host shadowDom>
      <style>
        {styleSheet}
      </style>
      <header ref=${ref}>
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
        <div>5</div>
      </header>
    </host>
  `;
}

Why use references?, References can be created from a custom-hook and allow limiting the dom manipulation context.

Note: the use of the styleSheet property as part of the virtual-dom(<host shadowDom styleSheet=${styleSheet}/>) has been deprecated, it will soon be available as a hook, for a better adoption of shadowDom between browsers it is better to use the tag style, eg:

function MyTag() {
  return html`
    <host shadowDom>
      <style>
        :host {
          color: black;
        }
      </style>
    </host>
  `;
}

I hope this is useful to you and I remain attentive to any question or recommendation.

srdjan commented 4 years ago

great! that worked... in use here: https://srdjan.github.io/ :)

thanks!