How to Integrate React with Ruby on Rails

React and Ruby on Rails Integration Tips

React.js is a Javascript framework popular for its simplicity. While other frameworks realize full Model View Controller approach, React realizes only Views.

React applications are based on two major principles: Components and States. The Components may consist of smaller built-in, or custom ones. The States principle stands for a one-sided data stream that will make the interface responsive to each state.

What React is loved for, is that it doesn’t need any additional dependencies in order to allow it to integrate with any Javascript library. We will use it to integrate React with the Rails Stack for creating the external interface.

In this article, we will consider the three ways of integrating React with Ruby on Rails: react-rails, react_on_rails, and Ruby gems along with Webpacker, and describe how you can build two separate applications for frontend on React and backend on Rails.

 

Why use React with Ruby on Rails backend?

Ruby on Rails with React is a super popular framework for a modern web application since both technologies are widely recognized in the development community. Let’s look at the benefits of incorporating React in a Rails stack for building a fast and scalable web application.

 

Related:

Pros and Cons of Ruby on Rails

Ruby on Rails for Web Development

 

Reliability

Both React and RoR are proven technologies that are widely used by well-known sites and have the support of an active development community. This makes React with Rails a highly reliable framework that is supported by the highest development standards.

Speed & Convenience

Ruby on Rails provides good number of gems that offer ready-made solutions for different tasks. It also provides the tools for building backend APIs that can communicate with the client-side, for example, with React frontend. The developers no longer need to write everything from scratch, so development speeds up, and the cost is reduced.

Lightweight

React is lighter than any other Javascript framework. When building the frontend, the developers use the structured components and add only those modules that are necessary. This helps to make the code precise and clear and reduce unnecessary lines.

Easy testing and maintenance

Comparing it with other technologies, Rails is a more convenient solution in terms of development, testing, and maintenance. The abundance of testing frameworks and libraries (Rspec, Capybara for Rails) and the distinct division between the two frameworks (backend on Rails and frontend on React) help to make the development and maintenance smooth.

Efficiency of teamwork

Since the application is clearly divided into the backend and frontend parts that are based on different technologies, communication within the team is improved by dividing the project into the areas of responsibility. React does not need to know that your frontend team knows the details of Rails, and vice versa – the work of the teams is handled separately.

 

Three ways to integrate React.js with Rails

 

1.React-rails gem and webpacker gem

Using the react-rails gem is the simplest and quickest way to integrate React into your Rails app. This gem uses the default Rails asset management and transforms JSX into the asset pipeline using the Babel transformer.

Webpacker is a gem offering smooth and standard integration of Rails with Webpack collector and the package manager Yarn. The optional integrations with popular frameworks and libraries like React, Angular, and Vue also come out-of-box.

For each Rails launching environment, there is a corresponding file in the config/webpack directory that is a part of the shared.js configuration that is common to all environments. There is also the configuration.js file that is responsible for processing the settings from config/webpacker.yml.

There are two installation scripts for launching the Webpacker installation process:

  • bin/webpack for one-time launching
  • bin/webpack-dev-server for launching the installation with tracking of file changing and re-build after modification. While developing your application, we recommend you use this variant.

Provided that you have already installed the latest version of Ruby and Rails, you are now ready to read our guide.

First, you need to add the gem to your gemfile by running the command gem 'react-rails' and install the gem by running bundle install and react-rails installation script: rails g react:install.

These actions will create a directory for the components and manifest file, and add them to the application.js file.

Once you have done this, create the .jsx React component file and save it in the directory app/assets/javascripts/components and run the code:

var HelloMessage = React.createClass({
render: function() {
return (
<h1>Hello {this.props.name}!</h1>
)
}
});

Later, use this component in the view with the help of the react_component helper method:

<%= react_component('HelloMessage', name: 'John') %>

It will add a div with the relevant classes and props that are later used by the react_ujs driver for mounting and rendering the component.

This method will allow you to start working with React gradually and test everything by converting the individual views into React components. Once you have achieved your goals, you can go to a more poverful setup.

2. react_on_rails gem

Another popular way to integrate React and Rails is with the react-on-rails gem. The key difference between this and react-rails is that it uses ECMAScript 6 (ES6) and state-of-the art tooling including Webpack by default, instead of relying on the Rails asset pipeline. This gem also does’t depend on jQuery.

To install Javascript libraries, instead of manually downloading gems, you can use NPM. Having integrated them, you will get more opportunities just for installing and managing several components.

In order to get started, install the node that will enable you to use NPM for launching Javascript dependencies. You can download the node directly from the website or install it by using NVM.

Having installed the node, we can add the gem to our Rails app and install it by running the bundle.


gem "react_on_rails", "~> 6"

In order to make the installation script work, we need to commit to this Git branch:


git init
git add -A
git commit -m "Initial commit"

Once you’ve done this, run the gem’s generator and create package.json and Procfile.dev files:


rails generate react_on_rails:install

Upon completing the above steps, run the bundle again in order to install exec.

Then launch the bundle once again (bundle && npm install) for installing execjs, and npm install for installing JS dependencies, and start the Rails server: foreman start -f Procfile.dev

The gem also creates a custom directory where all the client-side code is stored. Having set up everything we need, we can create and use the necessary React components.

 

3. Ruby on Rails API with ReactJS Front-End

 

Another way to integrate React with Ruby, is to make two separate applications for backend and frontend parts: the API part written on Rails and an application on React connected to the Rails API. This approach has the following advantages:

  • The frontend developers are allowed to use the Javascript libraries without needing to adjust their code to Rails constraints.
  • Since Rails API is communicating with the React interface via JSON files and there is no concept of sharing state to numerous servers, it will be easier to scale the application.

So, let’s see how we can connect the Rails API with the React frontend.

First, you need to create your Rails app structure and start the Postgres server by launching the corresponding app on your machine. Once this is done, you see the welcome page and the application is ready for the next step.

Inside the application folder, you need to create the client folder and React interface by using the create-react-app client. Inside this folder, you can use Yarn for performing the following actions as:

  • Yarn start for starting the development server (the React page can be accessed on http://localhost:3000/).
  • Yarn build for bundling the app into the static files for production.
  • Yarn test for starting the test runner.

Now, we will start the proxy for API calls via the necessary port without having to swap between development and production and restart the NPM server.

Later, you need to create the main active record relationships:

  • Scaffold the list resource by running rails g scaffold List title:string excerpt:text description:text upvotes:integer. In API mode, it will help to create migration, model, route, and controller.
  • The item resource can be created by running rails g scaffold Item type:integer name:string excerpt:text description:text url:string upvotes:integer.
  • For list item, we can create the join relationship by running the command rails g model ListItem list:references item:references description:text position:integer.

Having done this, it’s time to create and migrate the database by running the commands rake db:create and rake db:migrate.

Customize the namespaces by creating a folder app/controllers/api/v1 and copy the lists_controller.rb and items_controller.rb files to it. We have set up the proxy asking all calls beginning with /api to reach localhost:3001 where the Rails API is active instead of localhost:3000 where the NPM React client is working.

Once the API part is set up, it’s time to work with the React interface. Import  to App.js one and create a client/src/components folder where the components will be stored.

The next step is installing axios for making API calls: npm install axios. Now, import it to the ListsContainer by adding the line import axios from 'axios'. Also, you will have to redo an npm install, and quit and restart the npm server with npm start.

Then, let’s refactor the List part of the application by grouping the code into a component that does not handle the state, but receives data by props. To do this, create the list.js component:

import React from ‘react’;
const List = ({list}) =>

{list.title}

{list.excerpt}

export default List;

Then, import it from the main List component by running import List from './List'.

These are the three main ways to add React.js to the Ruby on Rails app. You are welcome to choose the one that fits the needs of your project best.

Read also: How to Get React and Django Work Together

Conclusion

Now know how to integrate React with the Rails app. Let’s make a brief recall:

    1. First, we considered the characteristics of React and the benefits of using it with your Rails backend: Owing to its reliability, speed, lightness of weight, and extensive documentation, the efficiency of the development team’s work will be increased.
    2. We also considered the three main ways of integrating React with Ruby on Rails: use react-rails and react-on-rails gems along with Webpack, and create two separate applications for the backend and frontend parts written on Rails and React accordingly. The last way is obviously the most complicated, yet it would be the best choice for the most complex projects with large development teams.

Hopefully, the article was helpful. Happy developing!

Contact us for help with your project.

get free consultation
Yaroslav Titenok

Yaroslav Titenok

COO

Subscribe to our blog