I'm trying to learn react.js, but got stuck on "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 index.html
file it works fine, but when I move it to seperate file I get blank page, and 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 it?
React is all about re-using code, and it is recommended to split your components into separate files. To do that, create a new file with a .js file extension and put the code inside it: Note that the filename must start with an uppercase character.
You no longer need to import React from "react" . Starting from the release 17 of React, JSX is automatically transformed without using React. createElement . However, other exports like hooks must be imported.
Yes. Possible to write all new code in TS but highly recommend migrating everything over to Typescript.
You get that error because:
index.html
from your local file system (e.g. by double clicking on it), instead of loading it via a web servertext/jsx
scripts is a javascript component that tries to fetch the file specified by the src
attribute of the script
tagfile://
protocol which is not within that list.When you included the jsx
script in the index.html
file it worked as no requests were needed in order to retrieve the jsx
script.
What you need to do is grab your hands on a web server, place the hello world files into the document root of that server, and load them from the web server, e.g. from an URL like http://localhost/index.html
.
I suggest you boot up a web server.
This python -m SimpleHTTPServer
will boot up a simple web server.
You can run this in your directory. Access it here http://localhost:8000
.
Or, you can use Chrome flags and add this line --allow-file-access-from-files
Notes
Python come pre-packaged with an OSX installation, so if you're on a Mac, good.
Chrome flags is not recommended as it is tedious of a process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With