Q: How can I add and remove Native web components based on viewport size? I want to add/remove the web components from DOM based on viewport size, let's say I have component A, which I want to add on Desktop, and when I resize the window ( shift to mobile view ) I want it to be removed.
can I use media-query here, if yes how?


class DesktopComponent extends HTMLElement {
    constructor(){
        super();
        this.shadow = this.attachShadow({ mode: "open" });
    }

    connectedCallback() {
        const template = `<div>Desktop Component</div>`;
        this.shadow.innerHTML = template;
    }
}

customElements.define('wc-desktop',DesktopComponent);

class MobileComponent extends HTMLElement {
    constructor(){
        super();
        this.shadow = this.attachShadow({ mode: "open" });
    }

    connectedCallback() {
        const template = `<div>Mobile Component</div>`;
        this.shadow.innerHTML = template;
    }

}

customElements.define('wc-mobile',MobileComponent);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <wc-desktop>
          <!-- this should be visible on Desktop only -->
    </wc-desktop>
    <wc-mobile>
          <!-- this should be visible on Mobile only -->
    </wc-mobile>
</body>
</html>



A: Media-queries can not remove DOM content; only do display:none.
You can check in the connectedCallback if CSS properties are set (by a media-query) or whatever check to test for Mobile/Desktop. And then do this.remove()


<template id="WC-DESKTOP">
  Desktop
</template>
<template id="WC-MOBILE">
  Mobile
</template>
<script>
  class ScreenSizeComponent extends HTMLElement {
    constructor() {
      super()  // sets AND returns the 'this' scope
        .attachShadow({mode:"open"}) // sets AND returns this.shadowRoot
        .append(document.getElementById(this.nodeName).content.cloneNode(true));
    }
    connectedCallback() {
      let isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
      let isDESKTOPonMobile = isMobile && this.nodeName.includes("DESKTOP");
      let isMOBILEonDesktop = !isMobile && this.nodeName.includes("MOBILE");
      if (isDESKTOPonMobile || isMOBILEonDesktop) this.remove();
    }
    disconnectedCallback(){
      console.log("removed DOM Element:",this.nodeName);
    }
  }
  customElements.define('wc-desktop', class extends ScreenSizeComponent {});
  customElements.define('wc-mobile', class extends ScreenSizeComponent {});
</script>
<wc-desktop>
  <!-- this should be visible on Desktop only -->
</wc-desktop>
<wc-mobile>
  <!-- this should be visible on Mobile only -->
</wc-mobile>


For more "removing Web Components" fun see: https://dev.to/dannyengelman/the-lt-site-head-web-component-you-never-see-in-f12-dev-tools-147f
