Express template engine based on React


Since Express allows you to build your own templating engine, I was curious if one could be developed with vanilla React.

Here are the steps that I took to build one.

Steps

Set up a minimal Express server.

Install React and ReactDOM:

npm install react react-dom

Create the templating engine:

// engine.js

var createElement = require('react').createElement;
var renderToString = require('react-dom/server').renderToString;

/**
 * Templating engine for Express.
 *
 * @param {String} filepath
 * @param {Object} props
 * @param {Function} callback
 */
function engine(filepath, props, callback) {
    try {
        var Component = require(filepath);

        // first argument is the error
        // second argument is the rendered view (html)
        callback(null, renderToString(createElement(Component, props)));
    } catch (error) {
        callback(error);
    }
}

module.exports = engine;

Set the templating engine for the Express app:

// server.js

// right after `app` is initialized...

app.engine('js', require('./engine'));

// the view files are JavaScript files, hence the extension
app.set('view engine', 'js');

// the directory containing the view files
app.set('views', './views');

Create a view:

// views/App.js

var React = require('react');
var App = React.createClass({
    render: function() {
        return React.createElement('h1', {}, 'Hello, ' + this.props.name + '!');
    }
});
module.exports = App;

Update the index route to render the view:

// server.js

app.get('/', function(request, response, next) {
    response.render('App', { name: 'world' });
});

Run the server to see it working at http://localhost:3000:

node server.js

Success!

Lastly, if you’re looking for a more fleshed out Express templating engine using React, then check out express-react-views and react-engine.



Please support this site and join our Discord!