Home > Mobile >  React not loading on html
React not loading on html

Time:04-07

I am trying to add react to a html page without node.

function Hello(){
    return (
        <div>
            <p>Hello World</p>
        </div>
    )
}

ReactDOM.render(<Hello />, document.getElementById('root'))
<!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</title>
</head>
<body>
    <div id="root"></div>
</body>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script type="text/babel" src="main.js"></script>
</html>

main.js is the javascript. Can you help me out with this? Thanks

CodePudding user response:

Maybe if you put the scripts inside the <body> it might work as the elements have to be loaded to be found by the selectors.

For example:

<body>
    <div id="root"></div>

    <!-- Scripts Here -->
</body>

In my browser (Firefox) it works!

CodePudding user response:

Use ReactDOM.createRoot(rootNode).render(<App />);

Reference- https://17.reactjs.org/docs/concurrent-mode-reference.html#createroot

CodePudding user response:

Okay, I don't know why this happens but this only happens when the react code is in another file.

<!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</title>
</head>
<body>
    <div id="root"></div>
    <div id="ot"></div>
</body>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script type="text/babel">
    var t = 0;
function App(){
  function enter(e){
    e.preventDefault()
    t  
   document.getElementById('ot').innerHTML = `You Clicked The Button ${t} times`
  }
  
  return (
    <div>
    <button onClick={enter}>Click me</button>
    </div>
    )
}

const root = document.getElementById('root');
ReactDOM.render(<App />, root)
</script>
</html>

So that works because for some reason react doesn't work for me in a different file, I have to use inline js. Thank you all for trying to help, and I hope I can help other poeple with this same problem. By the way, there were no errors in the console

  • Related