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)
2条答案
按热度按时间nbewdwxp1#
here is how to create a react component. note: a react component must has capitalized name.
rxztt3cl2#
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.
But if you still want to do all the configs by yourself, you can check this article:
Click