1 min read

Rails, React & Browserify (update)

In my previous article, I described a way to get the best of several worlds: Ruby on Rails, React JS and Browserify.
The intent was to keep using Rails as the great backend framework it is, but make it possible to embrace more advanced Javascript techniques thanks to Browserify as a module “packager” and React JS as a front-end framework.

This article has apparently been well received and raised the interest of many, si I wanted to push some quick updates about it:

  • I have published a sample Rails project on Github that implements what’s described in my original article. Feel free to use it as a starting point for your own projects ☺
  • Following a question on Twitter and a tip found in the article Setting up Rails with React and Jest (which happens to refer to my own article, thank you James Burnett!), you may be interested in making a small change to my original code in the application.js manifest:
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_self
//= require react_ujs

// Require React as a module and make it available globally instead of using the one provided by react-rails
React = require('react');

// Pull in our top-level components in the main javascript entry point

Instead of requiring React in a Sprockets directive, using the React lib provided by the react-rails gem, we instead require it as a Javascript module, thanks to Browserify.
Note that a new directive has been added, require_self, just before the inclusion of React UJS so that this useful script continues to work.

Doing so implies that we install React in our node modules:

$ npm install --save react

To minimize possible errors and conflicts, I’d suggest you make sure that this Node version of React matches the one provided with the react-rails gem.

This setup should allow you to use React and other libraries that need it much more freely!

Thank you all for your recommendations and mentions/messages on Twitter!

btn secont