简体   繁体   中英

ReactJs error: semicolon expected after render

I'm learning how to use ReactJs and I am at the very beginning.

I have a HTML file which is simply this

<!DOCTYPE html>
<html>

  <body>
    <div id="content"></div>

    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
    <script src="mainReact.js"></script>
  </body>
</html>

In the file mainReact.js this is my code

import React from 'react';
import ReactDOM from 'react-dom';

class Test extends React.Component {
  render() {
    return <h1>Hello World!</h1>;
  }
}

ReactDOM.render(<Test />, document.getElementById('content'));

I get an error next to "render(){" it says:

Multiple markers at this line -primary expression expected -semicolon expected

Could you please tell me what I'm doing wrong?

Thank you

First of all the line is JSX

<h1>Hello World!</h1>;

JSX will not be compiled directly by browsers, so you can transpile the code like

ReactDOM.render(
React.createElement('h1', {}, 'Hello World!')
, document.getElementById('content'));

Notice React.createElement('h1', {}, 'Hello World!') is the alternative version of <h1>Hello World!</h1> which browser understands natively.

Thus you will need a transpiler to do that automatically, so use bable

if you want to jump directly onto React and don't want to scratch your head with bundler and transpilers then its better to use

Create React App https://reactjs.org/docs/create-a-new-react-app.html

According to docs you have to use React.createElement .

If you check console it throws error import outside of module , you cannot use import because js files are not interpreted as ES modules, you must add in the nearest package.json that type has module value.

Check my update code below. Just change mainReact.js .

'use strict'
const e = React.createElement;

class Test extends React.Component {
  render() {
    return e('h1',null,'Hello World!');
  }
}

ReactDOM.render(e(Test), document.getElementById('content'));

A much easier solution is to run command npx create-react-app my-app read here

You can run npm init command to create a package.json file and then install Babel and webpack using npm. that should be able to do it. However that is a lot of work, I would suggest you to use create-react-app to create your project.

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