I need help understanding why this react code is not working

am fairly new to react and decided to follow along with a YT tutorial but am stuck at the introductory part

import React from ‘react’
import { ReactDOM } from ‘react-dom’
ReactDOM.render(<h1>Hello world</h1>, document.getElementById(‘root’));

the h1 text does not show up in my browser and there is no error message to the console. there was an error message but after including <script type="text/jsx" src="index.js"></script>, the error message disappeared but the h1 text is still not coming up. i also changed the script type to module but that does not work, what can i do please?

we may need the full code (meaning including HTML) to know for sure, but is there a <div id="root"></div> for ReactDOM to get? Also the curly brackets around ReactDOM is not needed as far as I’m aware. Hope that helps!

this is the HTML document

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div id="root"></div>
    <script type="text/jsx" src="index.js"></script>
</body>
</html>

Was this created through npx create-react-app?

no, the YT tutorial did not use npx

there was a security patch a few years ago that filtered the kind of file you are able to open with local file paths such as src='index.js'.

The fastest and easiest way to get around that is to initialize through create-react-app, and start your webpage through npm start instead of opening index.html.

This is assuming that you have the two files on a local machine. Sites like CodePen get around that automatically.

Here is a stackoverflow thread talking about what potentially could be your issue.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.