Home > Back-end >  React script is found but it won't render the simple hello world element
React script is found but it won't render the simple hello world element

Time:01-11

I'm new to react and i'm just testing out a simple render at the moment. I get no errors in the browser but nothing shows up on my screen that appears in my javascript react file.

html

<html>
    <head>
         <script  type="text/babel" src="reactfile.js"> testing</script>
    </head>
<link rel="stylesheet" href="/styles.css">
<body id="root">
    <p>react test</p>
</body>
</html>

react javascript file

import React from 'react';
import ReactDOM from 'react-dom';
class Helloworld extends React.Component {
  render() {
    return (
      <div>
        <p>Hello world!</p>
      </div>
    );
  }
}

ReactDOM.render(<Helloworld />, document.getElementById('root'));

CodePudding user response:

What you tell react with this line, is that you will put some HTML code inside the element with id root:

ReactDOM.render(<Helloworld />, document.getElementById('root'));

However, in your HTML code, there is not such an element. In order to make it work, just add this element (with the id root) to your page, like this:

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

Then, every code that your React code will produce will be put in this element.

CodePudding user response:

Make div with id "root" and add script tag below it. JavaScript can't access the root div before parsing it which means JavaScript can't find the element which doesn't appear in DOM tree. So you should put it script code at the end of line in body tag.

<body id="app">
    <p>react test</p>
    <div id="root></div>
    <script type="text/babel" src="reactfile.js"></script>
</body>

  •  Tags:  
  • Related