How To Use React as a Template Engine in Sails.js

Since I saw the other side of the coin, I felt in love with React. I’ve always loved componentization, and React allows you to componentize like a pro.

<<Angular, Ember and Knockout put “JS” in your HTML.
React puts “HTML” in your JS.>> - Cory House

That’s why when I returned to develop a more traditional web after being developing SPAs applications for a while, I missed so much React. Then, I remembered that you can use React in the server, but rendering a React application on the server adds a lot of overhead to a simple web page.

Luckily, you can use React as a kind of template engine. You will not have all the power that react brings to you, but at least, you could componentize your UI. This allows you to use composition in the views instead of the much more used approach, inheritance from base templates.

As I’ve been using Sails.js for my recent projects, this instructions are focused on this framework. But, it isn’t dificult to apply them to other frameworks as well.

Instructions

1 - Install express-react-views

$ npm install --save express-react-views react react-dom

2 - Change `engine` key in `config/views.js`.

engine: {
ext: 'jsx',
fn: require('express-react-views').createEngine()
}

3 - Create `index.js` in `views/` and put the following:

import React from 'react';  // You can even use ES2015!
export default () => (
<h1>Hello React</h1>
);

That’s it. If now you visit the URL pointing to this view, you should see your React component being rendered.


English is not my native language, and one of the objectives of this blog is to force me to write in english. So please, don’t hesitate to notice any mistake.