Server-side rendering with React
Let’s set up server-side rendering with React.
Prerequisite
Express
In your Terminal, create a directory for the project and change into it:
$ mkdir React
$ cd React
Install Express, a web framework for Node.js:
$ npm install express
Create a simple server.js
:
Start your server:
$ node server.js
Open the url in a browser (run command in new tab/window):
$ open http://localhost:3000
If you see the webpage, then that means your basic Express server is working. Go back to your Terminal and stop your server by pressing Ctrl+C
.
Addendum
If you plan to deploy your web app to service like Heroku, you’ll need to modify line 9:
var PORT = process.env.PORT || 3000;
This means use the port specified by the environment variable or 3000
by default.
Also, it’s recommended that you refactor your app so it’s more production-ready. Here are some tips for Express.
React
$ npm install react react-dom
Create Component.jsx
(not using JSX at the moment):
Refactor server.js
to render the component as a string:
Start the server again and confirm the result in the browser:
$ node server.js$ open http://localhost:3000
Babel
JSX is the syntactic sugar that makes React code look more like HTML. In order to use it, we’ll need to set up a compiler like Babel.
Install babel-register
, which will upgrade node’s require
hook:
$ npm install babel-register
Install babel-preset-react
, which will allow Babel to compile JSX to JS:
$ npm install babel-preset-react
Use Babel to transform required files from JSX to JS in server.js
:
Now refactor Component.jsx
and add some additional code:
Restart your server and view the result:
$ node server.js$ open http://localhost:3000
However, when you click the button, the alert doesn’t show. Why is that? That’s because the client-side portion is not set up. What’s missing is the component remounting in the DOM.
As a result, a client script needs to be built and loaded in the browser so the application can become universal/isomorphic.
The next tutorial will show you how to do that. Feel free to check out the code for this tutorial as well as other videos in my React playlist.