A simple "Hello World" in React.js not working

i just thought that i would share my solution with everyone. I wanted to set up a simple project without all the npm, node guff, like the OP i was having problems, it took me three hours to figure out, below is my solution.

HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Boy</title>
    <link rel="stylesheet" type="text/css" href="css/app.css">
    <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
    <script type ="text/babel" src="js/app.js"></script>
</head>
  <body>
    <div id="root">Loading...</div>

  </body>
</html>

The key is to include the appropriate script files from React and Babel. I am using an external app.js file, if you would like to do this then remember to include type ="text/babel".

Once done you can execute the hello world example from React. My app.js file:

ReactDOM.render(
    <h1>Hello, world!</h1>,
    document.getElementById('root')
  );

CSS file:

#root {
    color: skyblue;
}

I hope this helps.


Sol's answer covers why the simple hello app doesn't execute. The best practice on the latest React.js as of Jan 2017 is to import

<script src="https://unpkg.com/[email protected]/babel.min.js"></script>

and have the script type set to text/babel.

With this, you can execute JSX normally e.g.

class Greeting extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <p>Hello, Universe</p>
    );
  }
}

What you're missing is including something that transforms the JSX into JS. You need to include the JSXTransformer.js. Also notice the React.render doesn't use document.body, it should be a dom element. Here's an example that should work:

<!DOCTYPE html>
<html>
  <head>
    <title>My First React Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
  </head>
  <body>
    <div id="greeting-div"></div>
    <script type="text/jsx">
      var Greeting = React.createClass({
        render: function() {
          return (
            <p>Hello, Universe</p>
          )
        }
      });
      React.render(
        <Greeting/>,
        document.getElementById('greeting-div')
      );
    </script>
  </body>
</html>

Tags:

Reactjs