Node and npm handle the server-side components of the app. We will build a basic Express web framework serving Jade templated files, which is the default for the express-generator.
On the client-side, React will be used for the View layer. React lets you write your client-side code in clean javascript components, rather than mucking around with multiple blocks of html and scripts.
Set up the Express server
install dependencies:
$ cd demo-react && npm install
run the app:
$ DEBUG=demo-react:* npm start
Then load http://localhost:3000/ in your browser to access the app.
Set up the client-side React app
For React to work, it has to transpile it's .jsx componets. The easiest way to do this is with In-browser transformation. This method is not designed for production use, since it slows down the pages somewhat. But it's perfectly fine for dev and prototyping work.
We will use Bower to gather the React and Babel scripts needed for transformation.
Install Bower
Initialize bower, accepting the defaults.
We will make one customization here. Let's put the bower_components directory into the public
dir, for convenience.
Configure the Jade templates for React
Here's how you set up your Jade templates to include your React components.
The main views/layout.jade
needs to be updated to:
- source the react script,
- source the babel browser transformation script,
- and provide a new block called called
morejs
See the new bottom three lines in layout.jade
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
script(src='/bower_components/react/react.min.js')
script(src='/bower_components/babel/browser.min.js')
block morejs
In our views/index.jade
,
And the greeter component React JSX code itself, at /public/javascripts/helloworld.jsx
is:
React.render(
<h1>Hello, world from React.js!</h1>,
document.getElementById('greeter')
);
That's it. Refresh your browser at http://localhost:3000/ . You should see
Express
Welcome to Express
Hello, world from React.js!