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?

2
  • Are there any errors being thrown? Are you importing React and ReactDOM in main.js? Commented Feb 1, 2017 at 2: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. Commented Feb 1, 2017 at 17:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.