简体   繁体   中英

React JSX not being recognized?

I'm using these 2 CDN's to include React libraries in my project, however when I go to render some html using JSX onto the body of a HTML document it doesent recognize the JSX as JSX (I'm using chrome), and consequently throws up an error as it's reading the JSX as javascript. Am I doing something wrong? Any help would be great :) CDN's:

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

HTML:

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

React:

var React = require('react');
var ReactDOM = require('react-dom');
const text = <h1>Hello World</h1>;

ReactDOM.render(text, document.getElementById('here'));

You need a babel to use JSX .

Two ways to add babel to your project are,

  1. Add CDN for babel
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

Now you can use JSX in any <script> tag by adding type="text/babel" attribute to it.

For example,

<script type="text/babel">
   const text = <h1>Hello, world!</h1>
   ReactDOM.render(
      text,
      document.getElementById('root')
   );
</script>

Demo

  1. Install babel using npm ,

From the docs

Adding JSX to a project doesn't require complicated tools like a bundler or a development server. Essentially, adding JSX is a lot like adding a CSS preprocessor. The only requirement is to have Node.js installed on your computer.

Go to your project folder in the terminal, and paste these two commands:

Step 1: Run npm init -y (If you get an "Invalid name" error when you run npm init -y, rename the project folder to only contain lowercase ASCII letters or hyphens (e.g. my-project), and try again.)

Step 2: Run npm install babel-cli@6 babel-preset-react-app@3

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