Ad

A Simple "Hello World" In React.js Not Working

- 1 answer

I am making a simple "Hello World" program in React.js. I am expecting "Hello World" to be printed in the body of the html.

index.html

<html>
<head>
<script src="http://fb.me/react-0.12.2.min.js"></script>
<script>
var HelloWorld = React.createClass({
    render: function() {
        return <div>Hello, world!</div>;
    }
});
React.render(new HelloWorld(), document.body);
</script>
</head>
<body> 
</body> 
</html>

Error:

Uncaught SyntaxError: Unexpected token <

Can someone tell me where am I making a mistake?

Ad

Answer

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>
Ad
source: stackoverflow.com
Ad