I’ve been recently learning react on scrimba. I’m setting it up locally for a project. I can’t get it to work. I’ve installed react & react-dom via node.js . It’s not displaying anything.I did everything as follows to the react website for installation. I use vs code and I have live preview plugin
here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="index.js"></script>
</body>
</html>
here is my JS, I literally Copy pasted in "add React to exiting project" in the react website
import React from "react"
import ReactDOM from 'react-dom';
// Render your React component instead
const root = ReactDOM.createRoot(document.getElementById('app'));
root.render(<h1>Hello, world</h1>);
I get this error message when using live preview on the browser.
Uncaught SyntaxError: Unexpected token ‘<‘ (at index.js:6:13)
3
Answers
Have you installed the dependencies?
Run the following on the project root.
Try create-react-app util. It’s an easiest way to start using react.
Start a New React Project guide
By the way, your code running well and everything working on my local server. Maybe you should restart server or check files namings.
The first problem is that JSX doesn’t work in the browser. You will need to get some kind of transpilation going to use it. Some options you have for a premade solution:
You can also just use
React.createElement
so instead of:you could do:
The other problem is that the browser doesn’t know how to
import "react"
you may have import-maps set up but you didn’t say so, so I figured I’d mention it. Using one of the above tools will make this work as well. You will need tonpm install react react-dom
when using them. If you don’t want to use a tool like the above then you will need to setup import-maps or use full urls in your imports. You could also go the non-module approach for loading react.The react documentation you referenced has a lot more to say about it. I would recommend reading it in detail as well.
If you are just trying to get react working on an existing page quickly I would recommend loading it via cdn in global scope and using
React.createElement
instead of JSX.