Compiling JSX ReactJS code with Browserify and Reactify

This will be a very basic tutorial for those who are just getting to know React, by now you should have noticed that React uses JSX code, which is basically Javascript with some HTML elements. The problem here is that the browser cannot understand JSX, if you have already tried it you probably saw something like this on your firebug:

SyntaxError: expected expression, got ‘<'

In order to make it possible for the browser to interpret it we have convert the JSX into regular Javascript code, to achieve that we need to use tools like Browserify and Reactify.

Browserify, is a tool that let’s you use the function require(‘module’) in the front-end exactly like you do in the back-end with Node.js, then it compiles everything and generates a single JS file which will be referenced on your page. Reactify is pretty much the same thing, but it supports JSX code, Browserify alone wouldn’t be able to compile it.

Let’s take a look at an example, the first thing you need to do is to install both browserify and reactify:

1
2
3
4
5
//INSTALLS BROWSERIFY
npm install browserify
 
//INSTALLS REACTIFY
npm install reactify

Now, you probably have in you project a JSX file like this one (in my case it’s on the ‘src’ folder):

app.jsx

1
2
3
4
5
6
7
8
9
var ReactDOM = require('react-dom');
var React = require('react');
 
var HelloWorld = React.createClass({
 render: function() {
   return <div>Hello World!!</div>;
 }
});
ReactDOM.render(<HelloWorld />, document.getElementById('component'));

What you need to do now is to transform this into a JS file so the browser can read it, already with browserify and reactify installed just navigate to your project folder and type the following command:

1
browserify -t reactify src/app.jsx -o build/app.js

Perfect!! Now you have the app.js file in your ‘build’ folder, you can now use it in your HTML page like this:

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
   <head>
	   <title>React DataTable</title>
	   <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
   </head>
   <body>
	   <div id="component"></div>
	   <script src="build/app.js"></script>
   </body>
</html>

That’s it!! Hope I helped you with this tutorial, till the next one!!

Recommended for you

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>