Reaction - component in a separate script does not work

I am trying to learn response.js but am stuck in a "Hello World" script.

My index.html:

<!DOCTYPE html> <html> <head> <script src="https://fb.me/react-0.13.3.js"></script> <script src="https://fb.me/JSXTransformer-0.13.3.js"></script> </head> <body> <div id="example"></div> <script type="text/jsx" src="src/helloworld.js"></script> </body> </html> 

and src / helloworld.js:

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

When I put this code inside <script> in the index.html file, it works fine, but when I move it to a separate file, I get a blank page and a console error:

XMLHttpRequest cannot load file:///home/marcin/Projects/react/src/helloworld.js. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

What is wrong with him?

+5
source share
3 answers

You get this error because:

  • You downloaded index.html from your local file system (for example, by double-clicking on it) instead of downloading via a web server
  • The JSX transformer responsible for text/jsx scripts is a javascript component that attempts to extract the file specified by the src attribute of the script tag
  • Javascript is allowed to extract external resources only from the protocols listed in the error message (and even for those who have additional restrictions, such as cross-domain request); files downloaded from the local file system have the file:// protocol, which is not included in this list.

When you included the jsx script in the index.html file, it worked, since no queries were required to extract the jsx script.

What you need to do is grab your hands on the web server, put the world hello files in the root of the document of that server and download them from the web server, for example. from a url like http://localhost/index.html

+7
source

I suggest you download the web server.

This python -m SimpleHTTPServer load a simple web server.

You can run this in your directory. Access to it here is http://localhost:8000 .

Or you can use the Chrome flags and add this line --allow-file-access-from-files

Notes

  • Python comes preloaded with an OSX installation, so if you're on a Mac, fine.

  • Chrome flags are not recommended as this is tedious for the process.

+7
source

I know the answer is already approved, but for reference. We can use response.js with a script task like this

 <!DOCTYPE html> <html> <head> <script crossorigin src="https://unpkg.com/ react@15 /dist/react.min.js"></script> <script crossorigin src="https://unpkg.com/ react-dom@15 /dist/react-dom.min.js"></script> <script crossorigin src="https://unpkg.com/ babel-standalone@6 /babel.min.js"></script> <script type="text/babel"> ReactDOM.render( <h1>Hello, world!</h1>, document.getElementById('example') ); </script> </head> <body> <div id="example"></div> </body> </html> 
+1
source

All Articles