- In my previous post we have learn to use Isomorphic React JS with Express server.
- In this Demo, “We will learn to EJS template in Node Express Server and Isomorphic React JS”.
- We need to install express,react and ejs node modules to for this demo.In previous post we have already installed express and react.We need to install only ejs templating engine on the system.
- The EJS templating can be installed using npm install ejs –save command.The following screenshot shows the terminal with EJS installation in progress.
- The file structure for this demo is as following screenshot.The parent directory name is ReactIsomorphicDemo2.The EJS template index.ejs is present in views sub-directory.
- The HelloComponent.js file contains the react component which is shared between client and server.The code content of HelloComponent.js is as follows.
var React = require("react") var HelloComponent = React.createClass({ render:function(){ return React.createElement('h1', null, 'Hello Sandeep'); } }); module.exports = HelloComponent;
- The index.ejs contains the ejs template that can be displayed in the browser.The code content of index.ejs is as follows.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Isomorphic React JS with Express and EJS</title> </head> <body> <%- helloComponentMarkup %> </body> </html>
- The server.js contains the code for express server.It gets the index.ejs template and the react component sends it to the client.The code content of server.js is as follows.
var React = require("react"), myComponent =require("./HelloComponent"), express = require("express"), ReactComponent = React.createFactory(myComponent), expressApp = express(); expressApp.set('views', __dirname + '/views'); expressApp.set('view engine', 'ejs'); expressApp.get('', function(req, res){ var reactComponentMarkup = ReactComponent(), staticMarkup = React.renderToString(reactComponentMarkup); //res.send(staticMarkup); res.render('index', { helloComponentMarkup: staticMarkup }) }); var expressServer = expressApp.listen(80, function () { var serverAddress = expressServer.address(); console.log("express server started..."); console.log("express server host name: ",serverAddress.address); console.log("express listening to port no: ",serverAddress.port); });
- The express server can be started using node server.js command.The following screenshot shows the terminal with express server start in execution.
- The output of above demo in chrome browser which look like following screenshot.
- The demo code can be downloaded from the following link.
https://github.com/saan1984/ReactIsomorphicDemo2