2

I'm trying to learn React and I want to start with the simplest possible example. I got one from here: https://codeutopia.net/blog/2016/01/10/getting-started-with-react-the-easy-way/

But the code seems to refuse to load from the external .js file.

reacttest.html

<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.js"></script>
  </head>

  <body>
    <div id="app"></div>
    <script src="main.js" type="text/babel">
      // Code omitted to keep sample short
    </script>
  </body>
</html>

main.js

var App = React.createClass({
  render: function() {
    return <div>Something something Dark Side</div>;
  }
});

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

If I place the same code inside the script tags then it works fine. What am I doing wrong?

Adam
  • 518
  • 7
  • 17
  • Are there any errors being thrown? Are you importing `React` and `ReactDOM` in `main.js`? – KA01 Feb 01 '17 at 02:31
  • Yes. The error thrown was **XMLHttpRequest cannot load file://localhost/Users/username/react/main.js. Cross origin requests are only supported for HTTP.' ** By now I know that this is because of Chrome. – Adam Feb 01 '17 at 17:25

2 Answers2

1

If you are using Chromium based web browser, it will happen. You can try Mozilla Firefox or other Mozilla based web browser. Chrome will not allow react in this way. Moreover, 'type' (text/babel) attribute for script tag is deprecated. So, it is highly recommended to use react server or other server that support react.

S.M. Shakil
  • 159
  • 6
  • Found more info here: http://stackoverflow.com/questions/20904098/react-js-example-in-tutorial-not-working – Adam Feb 01 '17 at 17:03
0

I thought you could be using a HTML file without a server, so in that case when you try to import the file main.js you get an error, you could see an example working here: https://plnkr.co/edit/rlo7U99UVUF5HmzaHHE4?p=preview

<!DOCTYPE html>
<html>

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.js"></script>
    <link rel="stylesheet" href="style.css" />
  </head>

  <body>
    <div id="example"></div>
    <script src="script.js" type="text/babel"></script>
  </body>

</html>

Try to use a server to render your HTML file and should work.

damianfabian
  • 1,681
  • 12
  • 16