Thursday, December 27, 2018

React.js Basics

Start React.js

Add these lines to html to use React.js.
<script src="http://fb.me/react-0.13.3.js"></script> 
<script src="http://fb.me/JSXTransformer-0.13.3.js"></script> 

Pre-compile with jsx

To use React.js, you need to compile code. (If the code is not pre-compiled, the code can be automatically compiled and executed if you use jsx transformer:
<script src="http://fb.me/react-0.13.3.js"></script>
<script src="http://fb.me/JSXTransformer-0.13.3.js"></script>
But it is not recommended to use the un-compiled code in the production because of the performance problem.)
At first, install react-tools.
$ npm install -g react-tools
(If you don't have npm, install npm before this.)
Then create "src" and "build" folder in your current directory.
This is the React code:
ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);
Save this as helloWorld.js in src directory that was created in the current directory.
Compile the react as follows. This compiles jsx file of currrent directory and save the compiled file in dest directory:
$ jsx --harmony src/ build/
harmony option turns on JS transformations such as ES6 Classes etc. This command will generate compiled code to build directory. If you see inside the compiled file, it has javascript code.
You can call the compiled javascript like this:
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
     <div id="root"></div>
  </body>
</html>
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="./build/helloWorld.js"></script>
For React.js cdn links, see here.
You see the html file from a browser: