Saturday, February 14, 2015

Overview

I’ve heard some nice things about Facebook’s ReactJS Framework. So here’s how to setup React with Node. You can find more information here.

1
2
3
4
5
6
7
### in shell ###

# look at my bower tutorial on how to setup bower
$ npm install --save bower

$ npm install --save express-jsx
$ bower install --save react

React’s syntax is really verbose, so they use JSX. Manually compiling jsx is a pain so we’re going to use express-jsx which compiles the jsx in real time. Lets start.

1
2
3
4
5
6
7
8
// ### in app.js ###

// add near the top
var jsxCompile = require('express-jsx');

// order is important
app.use(jsxCompile(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

Now we’re going to modify the ejs file and make it use react.

1
2
3
4
5
6
<!-- ### in index.ejs ### -->

<div id="test"></div>

<script type="text/javascript" src="bower_components/react/react.min.js"></script>
<script src="javascripts/test.js"></script>

Remember that when test.js is requested, express-jsx middleware will look for a matching .jsx file. This means we need a test.jsx file.

1
2
3
4
5
6
7
8
9
// ### in test.jsx ###

/** @jsx React.DOM */
"use strict"

React.renderComponent(
  <h1>I am printing the title from react, works!</h1>,
  document.getElementById('test')
);

Random Posts