-1

So I have been learning my first lecture on React, and playing around with my code to understand how it works, But In code-pen my code is running, but in VS code it's not.

Here's the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="index.css">
    <title>Basic-React</title>
</head>
<body>
    <div id="root">not rendered</div>
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

    <script>
        // Your custom js code goes here
        const App = () => {
            return React.createElement(
                "div",
                {},
                React.createElement("h1",{}, "Adopt-me")
            )
        }

        ReactDOM.render(<h1>Karan</h1>, document.getElementById('root'))
        // ReactDOM.render(React.createElement(App), document.getElementById("root"))
    </script>
</body>
</html>

My ReacDOM.render call is giving an error on the browser as : index.html:25 Uncaught SyntaxError: Unexpected token '<'

But if run this code in codepen or say proper react-package installation with node, It's running Why?

Honey
  • 2,208
  • 11
  • 21
Thelostcause
  • 113
  • 7
  • Have you configured babel and webpack as well? Only adding react and react-dom libraries is not enough. If there is no babel, JS doesn't recognize

    syntax.
    – Tigran Petrosyan Jan 22 '21 at 07:33
  • I have not, I just used the CDN for react. – Thelostcause Jan 22 '21 at 07:40
  • React project configuration can be tricky if you are doing it for the first time. You need to configure webpack, which will bundle all your application, and you need babel. https://mustkeemk.medium.com/setting-up-a-react-environment-from-scratch-b992b28bbb2b You can read this article and do it by yourself, or you can use a nice abstraction npx create-react-app test if you have node installed. Or go to codesandbox and play there. – Tigran Petrosyan Jan 22 '21 at 07:45

2 Answers2

0

Your script tag that you embeded in your html is running native javascript. You need jsx support in order to write something like

<h1>Karan</h1>

in javascript. Use babel to transform jsx into javascript.

-1
const element = <h1>Karan</h1>;
ReactDOM.render(element, document.getElementById('root'));

Render dislike <> ;)

or

ReactDOM.render("<h1>Karan</h1>", document.getElementById('root'));
Mmx
  • 358
  • 4
  • 18