An error was encountered: "Uncaught SyntaxError: Unable to utilize import statement outside of a module in

I have come across the following code while learning React and trying to execute it.

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"
  }
}

Upon opening the browser, an error message is displayed:

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

This results in nothing being displayed on the browser. How can this issue be resolved? I attempted adding module to the script tag, however another error occurred:

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

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

Answer №1

Follow these steps to create a React component. Keep in mind that a React component should have a capitalized name.

const Header = () => {
  return (
    <header>
      <h1>Welcome to my website!</h1>
      <p>Explore and enjoy the content.</p>
    </header>
  )
}

const appRoot = ReactDOM.createRoot(document.getElementById("app-root"));
appRoot.render(<Header />);
<div id="app-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>

Answer №2

To properly bundle and transpile JSX into valid JavaScript code, essential tools like Webpack and Babel are required. These tools are readily available when initializing a project using frameworks such as CRA.

Browser's JavaScript engine cannot understand JSX, as it is not valid JavaScript.

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

If you prefer to handle all the configurations manually, you can refer to this informative article:

Explore Here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Restore the button to its original color when the dropdown menu is devoid of options

Is it possible to change the button colors back to their original state automatically when a user deselects all options from my dropdown menu? The user can either uncheck each option box individually or click on the "clear" button to clear all selections. ...

Editable content <div>: Cursor position begins prior to the placeholder

Having an issue with a contenteditable div where the placeholder text starts behind the cursor instead of at the cursor position. Any suggestions on how to correct this? <div id="input_box" contenteditable="true" autofocus="autofocus" autocomplete="o ...

The Firebase JQuery .on method is incrementally updating individual values in an array instead of updating them all simultaneously

I am trying to update the values of the orders placed by users on the Corporate's page without a refresh. I have implemented the jQuery .on method for this purpose. However, the values are being returned one by one from the array created for the order ...

Setting custom parameters ($npm_config_) for npm scripts on Windows allows for more flexibility and customization in

I'm struggling with passing custom parameters from the command line to npm scripts in my package.json file. Despite researching on various platforms, including Stack Overflow, I haven't found a solution that works for me. Here's what I' ...

Why is the toggle list not functioning properly following the JSON data load?

I attempted to create a color system management, but as a beginner, I find it quite challenging! My issue is: When I load my HTML page, everything works fine. However, when I click on the "li" element to load JSON, all my toggle elements stop working!!! ...

Discovering browser back button press event utilizing Angular

Can we identify when a user has navigated to a page using the browser's history back button? I am looking for a solution in angular.js without relying on angular routing. Additionally, it should also detect if a user returns to a form after submitting ...

Having trouble displaying information in a table using React JS

I devised a feature to display one column of a table and one column for checkboxes (each row should have a checkbox). I stored this file in a component folder with the intention of creating a page where the user selects an account type, and then a new tabl ...

What is the best way to identify the position of an element in an array given my specific circumstances

I am trying to utilize the ng-repeat directive in order to display an array. Here is what I have: <div ng-repeat="stu in school"> <div>{{stu.name}}</div> <div>{{stu.grade}}</div> </div> JavaScript $scope.scho ...

Removing the previous value in React by shifting the cursor position - a step-by-step guide

I have successfully created a phone using React that saves the numbers in an input field whether you press the keys or use the keyboard. Although the phone is functioning well, I am facing an issue where pressing the delete button or backspace key always ...

Unable to retrieve button value with material-ui package

My task requires me to retrieve the value of a button, as it contains an ID essential for further steps. Initially, I used a standard button with Bootstrap styling and everything functioned correctly. <button value={row.vacationRequestID} c ...

Creating animated reactions in discord.js is a goal of mine, however, I am encountering an issue that needs to

Last year, I asked this question and received helpful answers. However, there is still a problem that I couldn't figure out. Since I am unable to comment on the previous answers, I have decided to add a new question client.on('message', mess ...

How to Set a Background Image for a Div in React?

render(){ const { classes } = this.props; const { imageDescription } = this.props.imgDesc; const { currentIndex } = this.state; var fullPath = `../images/Large/${(imageDescription[currentIndex]).imagePath}.jpg`; con ...

What is the most effective method for synchronizing data with HTML5 video playback?

I am currently developing a program that retrieves data from an android application and plays it back on a web browser. The android app allows users to record videos while logging data every 100ms, such as GPS location, speed, and accelerometer readings, i ...

What is the best way to adjust the width of a nextui dropdown menu?

I'm having trouble changing the width of the nextui dropdown. I attempted to use classNames prop like this, but it doesn't seem to be working: ` <DropdownMenu classNames={{ base: "max-w-[100px]" }} disallowEmptySelection selectionMod ...

Code not functioning properly in Internet Explorer

In one of my JavaScript functions, I have the following CSS line which works well in all browsers except for IE (Internet Explorer). When the page loads, the height of the element is only about 4px. element.setAttribute('style', "height: 15px;") ...

Ordering an Array of JavaScript Objects in a Custom Sequence (utilizing pre-existing methods)

Imagine we have an array of objects: ["c", "a", "b", "d"] Is there a way in ECMAScript or through a third-party JavaScript library to rearrange the objects in the first array to match the order specified by the second array, all within one line or functi ...

Modify the CSS when CKEditor is in focus

Implementing CKEditor in a symfony project using the FOS\CKEditor-bundle 1.2. I want to style the entire element containing CKEditor with a border when it is focused, similar to how questions are written or answered on Stackoverflow. By referencing a ...

Slide the next section over the current section using full-page JavaScript

I'm currently developing a website utilizing the FullPage.JS script found at this link . My goal is to have the next section slide over the previous one, similar to what is demonstrated in this example. I've attempted setting the position to fix ...

SwipeJS is not compatible with a JQuery-Mobile web application

I am currently attempting to integrate SwipeJS (www.swipejs.com) into my JQuery-Mobile website. <script src="bin/js/swipe.js"></script> <style> /* Swipe 2 required styles */ .swipe { overflow: hidden; ...

Determining the appropriate version of the types package for your needs

It has come to my attention that certain npm packages do not come with types included. Because of this, the community often creates @types/packagename to provide those types. Given that both are packages, how does one determine which version of the types ...