Ruby on Rails has been an extremely productive monolith web application (full-stack) framework that enables developers to develop and deploy applications with ease. For businesses and startups, it serves as a platform that helps to get the product to the market quickly.
Ruby on Rails used to ship with jQuery by default (until version 5.1), jQuery is a great library that is small and robust. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax simple with an easy-to-use API.The plugin architecture is also very nice for extensibility and has a wide community support.
But for applications where performance is a key factor, the DOM-manipulation has been a bottleneck as it requires traversing the entire document (web page) in order to change/update a part of the view. Another bottleneck is the actual refresh of the page, which requires the assets to be loaded along with the actual content of the page. One of the ways to handle this is through Single Page Applications (SPA's).
Some of the best and popular front-end technology stacks are -
- React
- AngularJS
- Vue.js
- Ember.js
In this blog, we will see some of the ways in which we can integrate React with Ruby on Rails.
React - For Fast User Interfaces
React is a JavaScript library created and maintained at Facebook for building user interfaces, which aims to be declarative, making the code more predictable and easier to debug. React can be thought of the "V" (View) in "MVC" (Model, View, Controller architecture/design pattern). Views are modeled as components, the advantage of this that, we can pass rich data through the app and maintain state outside the DOM.
Integrating React with Ruby on Rails
1. react-rails gem and webpacker gem
I find
react-rails
gem is by far the simplest way to get started with React and JSX in a rails application.It uses Ruby on Rails asset pipeline to automatically transform JSX into Ruby on Rails compatible assets using the Ruby Babel Transpiler.
For advanced use cases, one could integrate
react-rails
gem withwebpacker gem
to integrate webpack with Rails usingReactRailsUJS
.Another upside of using this gem is that is compatible starting from Ruby on Rails 3.2+
Let's see how to integrate this with an existing Ruby on Rails application.
Implementation.
Assuming you have a Ruby on Rails application. We can start by adding the gem to our dependencies.
# Gemfile
.
.
gem 'react-rails'
.
Install the Gem with
bundle install
Run the generator.
rails g react:install
This gives us a components
directory under app/assets/javascripts/
, a manifest file and adds them to our application.js
's dependency.
We can now create a simple component by creating a file under the components
folder, let's call this greet_user.jsx
// app/assets/javascripts/components/greet_user.jsx`
window.GreetUser = React.createClass({
render: function() {
return (
<h1>Hello {this.props.name}!</h1>
)
}
});
This component can be invoked from any of the views, like so.
<!-- app/views/greet/index.html.erb -->
<%= react_component('GreetUser', name: 'Icicle') %>
<!-- becomes: -->
<div data-react-class="GreetUser" data-react-props="{"name":"Icicle"}"></div>
The helper
react_component
identifies the actual component by the name of the componentGreetUser
and acceptsprops
as the second argument.
That is all that it takes to integrate React with Ruby on Rails using the react-rails
gem. It also allows high customization, ES6 components, and server rendering to name a few. All of which are explained in detail in the official documentaion.
2. react_on_rails gem
React on Rails gem is another popular gem, that helps in integrating React with Rails. I feel this is a good choice for developers who are aware/comfortable with javascript toolings like
webpack
. The main difference thatreact_on_rails
gem brings to the table is that it allows us to create React Components using ES6 and it uses webpack to compile the React components to JS that is understood by Rails, as opposed to relying on the Rails assets Pipeline.Since we have the power of webpack, we could configure it as per our needs but the drawback is that one needs to install tools like
npm
and understand howwebpack
works.
To get started with this Gem, we first need nodejs
, as the gem will be using npm
to download and install the necessary JavaScript dependencies.
Install instructions for NodeJS can be found on NodeJS website.
Once
node
andnpm
have been installed we can start by adding the gem to our Gemfile.
Gemfile
gem "react_on_rails", '8.0.0' # use latest gem version, prefer exact version
Install it by running
bundle install
NOTE We need to have
git
and commit our work (or rails generate will not work properly when generating react_on_rails)
git add --all
git commit -am "Adding react_on_rails gem"
We can now run the generator to install and setup the folder structures.
rails generate react_on_rails:install
Then run bundle again for installing
execjs
andnpm
dependencies.
bundle install && npm install
We can now start our rails server using
foreman
.NOTE react_on_rails internally depends on
forman
, This is required to not only start an instance of the Rails server but also start Webpack and configure it to watch and compile our javascript changes.
foreman start -f Procfile.dev
A simple HelloWorld component is generated when we run the generator and can be found under the
app/client
folder. This can be seen by visiting http://localhost:5000/hello_world
3. Ruby on Rails API
with ReactJS
Front-End.
The other option that is available to use ReactJs with Ruby on Rails is to use Ruby on Rails as an API only application and use React as a standalone application which talks to the Rails API.
Developing and Maintaining such a stack which separates out the backend application for the front-end might look daunting, but such a stack does have its advantages.
Helps Separation of Concerns. Allowing the front-end team to utilize the vast JavaScript libraries available without being bogged down by the constraint of Rails.
Allows ability to bring in other clients such as a mobile application, which also talks to the same Rails API that is responsible for serving data to the Web interface.
Easier to scale, assuming we are looking at the Rails API to be communicating over JSON we will not have the concept of sharing state across the many server instances that we might have.
4. Ruby-hyperloop gem (The easiest way to integrate React with Ruby on Rails)
Ruby-Hyperloop allows you to create React components using Ruby code. Thus allowing Ruby developers to be more productive and make development a lot faster. The advantage this gem brings to the table is that almost almost all React components are is done using Ruby code, from the creation of a component to Routing and even Testing (using rspec). This makes not only the backend but also the front-end the same technology stack.
The Gem has been tested for versions of Rails (~> 4.2), Rails (~> 5.0) and the last Rails (5.1.0).
Hyperloop Setup.
Add hyperloop to the Gemfile.
# Gemfile
.
gem 'hyperloop'
.
.
Once the gem is added. Let us now install it with.
bundle install
Hyperloop gives us a generator to update the JavaScript dependencies and to generate the required folder structures.
rails g hyperloop:install
The generator creates the hyperloop structure inside the /app directory :
/app/hyperloop/
/app/hyperloop/components
/app/hyperloop/models
/app/hyperloop/operations
/app/hyperloop/stores
And also updates our app/assets/javascripts/application.js file adding this line:
// app/assets/javascripts/application.js
// Other requires
.
.
.
//= require hyperloop-loader
We can now test it by creating a very simple Component by running the hyperloop generator:
rails g hyper:component Helloworld
This would have created a new Component under
app/hyperloop/components/
Let us add a route in
routes.rb
get 'helloworld' => 'hyperloop#helloworld', as: :helloworld
Starting Rails server with
rails s
and visitinghttp://localhost:3000/helloword
will show us the generated component.
For further reference on hyperloop
I highly recommend going through the Ruby-hyperloop website, which has a detailed documentation on creating components, routes and managing state in the application.
Hope this blog was of help in understanding how to integrate React and Ruby on Rails. Though there are many other ways in which React JS could be integrated with Ruby on Rails, I have shared only a few that I have found not only easy to get started with but also which has a good backing from the community.