1

Hi I am new to React and found out that we can use React by adding its required scripts in our main index.html file. So, I did all the required steps to add script and also made sure to include babel, because I am writing my main App in JSX. But an error from Babel keeps coming up 'Uncaught ReferenceError: require is not defined' pointing to my import statement where I import React and ReactDOM.

Code files:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>React-1</title>
</head>
<body>
    <div id="root"></div>
    <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script type="text/babel" src="App.js"></script>
</body>
</html>

App.js

import { React, ReactDOM } from "react";
function Counter() {
  return <h1>Hello World!</h1>;
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(Counter);

Folder Structure:

-->index.html

-->App.js

0

1 Answer 1

3

You don't need to import React when including it directly from a CDN.

<script type="text/babel">
function Counter() {
  return <h1>Hello World!</h1>;
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Counter/>);
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer! Can you please explain why importing is not necessary?
@manusrao Because you're using the browser version of it, which provides React and ReactDOM as globals.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.