Home > Blockchain >  Uncaught SyntaxError: Cannot use import statement outside a module for React
Uncaught SyntaxError: Cannot use import statement outside a module for React

Time:12-08

I have the following code that I am trying to run as part of learning React.

HTML

<html>
    <head>
        <link href="index.css" rel="stylesheet">
    </head>
    <body>
        <div id="root">
        </div>
    <script src="index.js"></script>
    </body>
</html>

Javascript

import React from "react"
import ReactDOM from "react-dom"

const navbar= (
    <nav>
        <h1>Alchamentry</h1>
        <ul>
            <li>Pricing</li>
            <li>About</li>
            <li>Contact</li>
        </ul>
    </nav>
)
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(navbar)

package.json

{
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  }
}

Now when I open the browser, I get the following error:

index.js:1 Uncaught SyntaxError: Cannot use import statement outside a module (at index.js:1:1)

and nothing is displayed on the browser. How to fix this? I tried to add the module to the script tag, but it is giving another error that says

<script src="index.js" type="module"></script>

index.js:1 Uncaught SyntaxError: Cannot use import statement outside a module (at index.js:1:1)

CodePudding user response:

here is how to create a react component. note: a react component must has capitalized name.

const Navbar = () => {
  return (
    <nav>
      <h1>Hello, i am NavBar. Nice to meet you. And here are my links</h1>
      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Profile</a></li>
      </ul>
    </nav>
  )
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Navbar/>);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

CodePudding user response:

You need tools like Webpack and Babel to bundle and transpile jsx to valid JavaScript code. Such tools come out of the box if you try to create a project with packages like CRA.

This jsx isn't valid JavaScript and is not understood by browser's JavaScript engine.

    const navbar= (
    <nav>
        <h1>Alchamentry</h1>
        <ul>
            <li>Pricing</li>
            <li>About</li>
            <li>Contact</li>
        </ul>
    </nav>
)

But if you still want to do all the configs by yourself, you can check this article:

Click

  • Related