With the release of Rails 5.1 and the integration of webpack and yaml into rails all that is described here can be done much more simply using what is integrated into rail. That said, if you can’t upgrade yet or require serverside render the solutions below are still great options for you.
While the dawn of the large JS frontend app is long past and there is a new magical unicorn and pixi dust JS framework every time you turn around, there are still a lot of stock standard web apps out there. As a web consultancy, these apps have been our bread and butter for quite some time and there is no real need to change them. They just work.
But as things change, it would be nice to add some of the dynamic features of the new javascript hottness to our standard rails apps. Here are a few ways to integrate React into rails.
Notice: there is going to be a stupid amount of alliteration in this post. Fair warning. React rendering in Rails rendered radical web app.
React-Rails gem
I am starting here because this is the easiest way to get started with React on Rails. Per usual, just include the gem in your gem file gem react-rails
, bundle install
, and then run the install generator rails g react:install
.
The reason I say this is it is fully integrated with sprockets and the current rails asset pipeline. if you already understand the asset pipeline and helper methods, then you’re good to go. Also, there is no dependacy on npm.
This is all you need to mount a React component to a spot on the page. That is this helper react_component
.
<%= react_component("MyCoolWidget", prop1: "123", prop2: "abcd") %>
Other features include the ablitiy to render the components on the server for faster rendering and SEO, rendering a component as a view, and writing your components in ES2015 syntax or CoffeeScript.
One problem to note is that this doesn’t support a module system for JavaScript like Common-JS or ES6 imports. So, working with packages for React that do not have a version that does not export a useable variable is difficult.