-1

I am currently having an issue with custom elements, I am building some custom stuff to go on an ecommerce website and one of my custom elements is re-rendering itself multiple times.

window.initDealBadge = function(customer) {
class DealBadgeCustomElement extends HTMLElement {

    constructor(){
      super();
    }

    connectedCallback(){
      console.log("ELEMENT ADDED TO PAGE")
      const mountPoint = document.createElement('span');

      this.appendChild(mountPoint);

      const attrs = [].reduce.call(this.attributes, (memo, attr) => {
            memo[attr.name] = attr.value;
            return memo;
        }, {});
        const data = Object.assign({}, attrs);

      ReactDOM.render(<DealBadge customer={customer} id={data.id}/>, mountPoint);
    }
  }
customElements.define('deal-badge', DealBadgeCustomElement);

}

This is my first time working with Custom elements, has anyone came across this issue before?

Thank you

Robert Templeton
  • 139
  • 1
  • 2
  • 9

1 Answers1

0

I managed to get it working, ConnectedCallback was being called multiple times. I added in a count to ensure it only runs once.

window.initDealBadge = function(customer) {
class DealBadgeCustomElement extends HTMLElement {

    constructor(){
      super();
      this.count = 0
    }

    connectedCallback(){
      if(this.count === 0){
        this.count += 1
        console.log("ELEMENT ADDED TO PAGE")
        const mountPoint = document.createElement('span');

        this.appendChild(mountPoint);

        const attrs = [].reduce.call(this.attributes, (memo, attr) => {
              memo[attr.name] = attr.value;
              return memo;
          }, {});
          const data = Object.assign({}, attrs);

        ReactDOM.render(<DealBadge customer={customer} id={data.id}/>, mountPoint);
      }
    }
  }
customElements.define('deal-badge', DealBadgeCustomElement);};
Robert Templeton
  • 139
  • 1
  • 2
  • 9
  • 1
    I'm curious why connectedCallback is running multiple times on page load. This is happening to me as well, which is frustrating. My problem, however, is that connectedCallback is running before the `id` attribute is parsed, which is causing an issue. Do you know why it was being called multiple times? – Hanzy Sep 23 '20 at 16:15