0
votes

In React Application I want to use web component while using it I am getting an error

TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

I have used web component in one of my project where I have reacted version 16.12, Web component works perfectly while project which has React 16.13.1 version it shows error

I index.js I have imported web component.

Index.js file

import "./webComponent/ImperativeCounter";

ReactDOM.render(
  <TranslateProvider translations={translations} defaultLanguage={"sp"}>
    <Provider store={store}>
      <MainApp />
    </Provider>
  </TranslateProvider>,
  document.getElementById("root")
);

mycomponent.js

      <section>
        <i-counter ref={counterElement}></i-counter>;
      </section>

web component

class ImperativeCounter extends HTMLElement {
  constructor() {
    super();
    this.shadow = this.attachShadow({ mode: 'open'});
    this.currentCount = 0;
    const templete=`
     <b>Count:</b> ${this.currentCount}`;
    this.shadow.innerHTML = template;
  } 
}
window.customElements.define("i-counter", ImperativeCounter);
1
@demkovych after installing "custom-elements-es5-adapter": "^1.0.0", still it gives the same errorSaif Farooqui
change the target in the tsconfig.json or jsconfig.json file to es6. Are you using webpack? If yes, what babel version you are using?demkovych
i don't have tsconfig.json file in my React version of babel is 6.26.0Saif Farooqui
how do you build your app? Do you use webpack?demkovych

1 Answers

0
votes

Looks like transpiling problem. First install these 2 plugins (if you are using babel 6.*):

npm i --save-dev babel-plugin-transform-es2015-classes babel-plugin-transform-custom-element-classes babel-preset-es2015 

then try to add them to your webpack.config:

{
  loader: 'babel-loader',
  options: {
    presets: ['es2015'],
    plugins: ['transform-custom-element-classes', 'transform-es2015-classes']
  },
}