aZero
aZero

Reputation: 17

Why JSX doesn't run while React works with no problems

First thing I'd like to say is that I'm obviously new to React. I did the set up like they said on their website, even for JSX.

When I paste their code it runs, but when I add JSX it doesn't work at all. I've got node.js on my computer too and I've retried it several times but no way. The console says: Uncaught SyntaxError: expected expression, got '<'.

If anyone have any clue why this is not working it would be really helpful. This is my code:

HTML:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <link rel="stylesheet" href="./index.css">
    <link href="https://fonts.googleapis.com/css2?family=Nova+Mono&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Anton&display=swap" rel="stylesheet">
</head>
<body>

    <div id="back-body">
        <div id="main-canvas">
            <div id="root"></div>
        </div>
    </div>

    <!--React-->
    <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>
    <!--Babel-->
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script src="./index.js"></script>
</body>
</html>

JS File:

'use strict';

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);

Thank so much! :)

EDIT

I found out the problem after watching this video: https://youtu.be/ahh65GQz74g

Basically, I didn't set up Babel correctly as I wasn't placing the folders properly. Plus I left the Babel script in my HTML, which shouldn't be there. If someone else comes here with the same problem, I recommend to do exactly what that video says.

Thanks everyone for your help!

Upvotes: 0

Views: 747

Answers (2)

lucasreta
lucasreta

Reputation: 938

Adding the following attribute to your final script tag should do the trick:

<script type="text/babel" src="./index.js"></script>

It's important to note that this isn't a good practice for production environments, as client-side compiling is slow and wasteful, so you should consider precompiling your scripts and setup your project accordingly.

Update: try modifying the source of babel to the following:

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

Upvotes: 2

Gabriel Nadaleti
Gabriel Nadaleti

Reputation: 1646

Maybe adding "text/babel" and its presets work as well

<script type="text/babel" src="./index.js" data-presets="es2015,react"></script>

Upvotes: 0

Related Questions