Isomorphic React with Node/Express

May 15, 2015

Lately I have finally got round to make an isomorphic React app. Meaning that the app is initially rendered on the server and then passed to the client as html which is rendered and then React takes over.

At the simplest level setting up React isomorphically is very easy.

First we need our React component:

1// App.react.js
2
3import React from 'react';
4
5class App extends React.Component {
6 render() {
7 return (
8 <p>Hello, World</p>
9 )
10 }
11}
12
13export default App;

For our client side rendering the React.render statement isn’t touched. However we need to tell our server to spit out the React component when we hit the app.

To do this we need to set up an index file in a template language of your choice. I chose Jade for no reason specifically.

1<!DOCTYPE html>
2 <html>
3 <head>
4 <title>Hello world Isomorphic body</title>
5 </head>
6 <body>
7 <section id="app"></section>
8 </body>
9 <script src="dist/bundle.js"></script>
10</html>

You will notice that in our section with id app we have a html variable. This is what we are going to pass our rendered React component to from Node.

Now onto the server, we need to set up a few things first:

1require('babel/register');
2const express = require('express');
3
4const app = express();
5const path = require('path');
6var React = require('react');
7
8app.set('view engine', 'jade');
9app.set('views', path.join(__dirname, 'templates'));
10app.use('/dist', express.static(path.join(__dirname, 'dist')));
  • Babel is used for ES6 to ES5 transpiling
  • Set up our Express app
  • Import React
  • Set our view engine to Jade
  • Tell Express where to find our Index file
  • Then tell Express where to find our bundle file

Now we can send our rendered component down!

1var App = React.createFactory(require('./App.react'));
2
3app.get('/', function(req, res) {
4 var markup = React.renderToString(App());
5 res.render('index', { html: markup });
6});

First we import our App component and then use the React helper to render it to a string.

Next we pass it to the index file that we made earlier which will print it out.

And then serve the express app.

1...
2
3app.listen(3000)

Nice!

Contact.

LET'S WORK

TOGETHER

I am open to both contract and freelance developer projects and would love to hear what your ideas are.

Feel free to drop me an email and I'll let you know how I can help you!

mail@benstokoe.co.uk