简体   繁体   中英

Unexpected token '<' when trying to load my webcomponent in html

so im trying to create a react webcomponent. I wrap it and on VSCode looks fine, but when I'm trying to load it, it gives me the error: Unexpected token '<' on the line:

ReactDOM.render(<Counter/>, mountPoint);

Does anyone know why and how to fix it? thanks

This is my WebComponent:

import React from 'react';
import * as ReactDOM from 'react-dom';
import Counter from './counter';

class CounterWC extends HTMLElement {
    connectedCallback() {

        // Create a ShadowDOM
        const root = this.attachShadow({ mode: 'open' });

        // Create a mount element
        const mountPoint = document.createElement('div');

        root.appendChild(mountPoint);

        // You can directly use shadow root as a mount point
        ReactDOM.render(<Counter/>, mountPoint);
    }
}

customElements.define('counter-wc', CounterWC)

And this is my html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-9" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>React webcomponent:</h1>
    <counter-wc></counter-wc>
    <script type="module" src="./counterWC.js"></script>
  </body>
</html>


Re: comments

The fact that you name your file *.js doesn't mean it is JavaScript

ReactDOM.render(<Counter/>, mountPoint); is JSX, not JavaScript, it needs to be converted in a Build step to JavaScript.

Or do not use React at all:

 class CounterWC extends HTMLElement { constructor(){ super().attachShadow({mode: 'open'}).append(this.div = document.createElement('div')); } connectedCallback() { this.div.innerHTML = `Am I a counter?`; } } customElements.define('counter-wc', CounterWC);
 <counter-wc></counter-wc>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM