Contact Us
#Tech | 12 min read | Updated: 11/29/2024

React and Ruby on Rails Integration Tips

Updated: 11/29/2024
, Lead Ruby on Rails Developer
#Tech
12 min read

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

Here at Sloboda Studio, we practice a large number of possible React + Rails Combos. In this article, we will describe how you can build two separate applications utilizing Ruby on Rails with React.

Here at Sloboda Studio, we practice a large number of possible React + Rails Combos, but let’s review the most common options for a quick start:

React-Rails, React_on_Rails, and Ruby gems along with Webpacker.

We will describe how you can build two separate applications for frontend on React and backend on Rails.

Why Ruby is Popular in 2024?

In 2024, Ruby continues to be a popular choice for developers thanks to its ability to streamline the application development process. So, add this language to your roster!

Ruby’s syntax, known for its readability that feels close to natural language, allows developers to create code that’s easier to understand and maintain. This translates to faster development cycles, and enables to add it to the vast ecosystem of libraries and gems offered by the Ruby on Rails framework.

These pre-written code modules act as building blocks, letting developers create and add features and functionalities with just a few lines of code. With a strong and supportive community constantly that can help devs to create and add new gems and keep the language up-to-date, Ruby empowers developers to focus on innovation.

This enables them to create robust applications. Thus, they can create and add complex features by using a special type of command or add functionality by importing an existing gem – that’s the 10x development boost Ruby offers.

Getting started with Ruby is a breeze too. With a single command, developers can create a new Rails app, complete with the basic file structure for controllers, models, and views. These components act as the building blocks of your application, allowing your developers to add lines to the code. But Ruby on Rails offers even more convenience. Using a simple command, you can further customize your app’s structure. For instance, another command can generate new controllers, mode+ls, or views to handle specific functionalities within your application. The command can not only save time but also ensure consistency throughout your codebase. Finally, a command can exist to manage your app and database and migrations, ensuring your data structures stay in sync with your application’s evolving needs. This focus on streamlined development through a well-defined command makes Ruby on Rails a favorite among developers.

Ruby on Rails offers a structured approach to app development using a set of core files. Following a command, you can use Rails to generate the needed file, forming the foundation of your app. Let’s explore some of these essential building blocks:

  • Controllers: This type of a file acts as the traffic directors of your app, handling incoming requests from users and interacting with other parts of the app, like models and views. Imagine this file as the switchboard operators, figuring out where to route each user interaction.
  • Models: This file represents the data of your application. Think of this file as a blueprints that defines the structure and properties of your data, such as users, products, or blog posts.
  • Views: Such file is responsible for presenting information to the user. It uses code templates and imported components to dynamically generate the HTML, CSS, and JavaScript that users see in their web browsers.

Usually, every file would work together seamlessly. Controllers receive user requests, interact with models to access and manipulate data, and then use views to present the resulting information in a user-friendly format.

So, whether you’re building a simple web app or a complex enterprise solution, Ruby provides the tools and resources to get the job done efficiently.

Can React and Ruby on Rails Work Together?

React and Ruby on Rails can work together in a complementary manner. React can be used for building the frontend user interface, while Ruby on Rails can handle the backend logic and database management. They can communicate through APIs to create dynamic and interactive web applications.

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 Ruby on 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 React and Ruby 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 the 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. Here 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. If you want to create the best application, we recommend you use this option.

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

First, you need to add the new 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 new 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 to test everything by converting the individual views into React components. Once you have achieved your goals, you can go to a more powerful setup.

2. react_on_rails gem

Another popular way to integrate React and Ruby on 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 doesn’t depend on jQuery.

To install Javascript libraries, instead of manually downloading gems, you can use NPM. Having integrated them, you will have more opportunities for installing and managing several components to merge Rails and React.

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 Ruby on Rails app and install it by running the bundle.


gem "react_on_rails", "~> 6"

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 the 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 able 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.

Let’s go over how we can connect the Ruby on Rails API with the React frontend.

First, you need to create your Ruby on 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 new client folder and React interface by using the create-react-app client. Inside this folder, you can use Yarn to perform the following actions as:

  • Yarn start for creating and starting the development server (the React page can be accessed at http://localhost:3000/).
  • Yarn build for bundling the app into 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

Why use React JS and Ruby on Rails backend?

Rails with React is a super popular framework mix 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 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 a 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 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 to reduce unnecessary lines.

Easy testing and maintenance

Compared with other technologies, Rails is a more convenient solution for 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 areas of responsibility. React does not need to know that your frontend team knows the details of Rails, and vice versa – the teams’ work is handled separately.

Conclusion

You just checked out the most common ways to integrate Ruby on Rails app and React. Let’s summarize briefly:

  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.

Surely, there are many more interesting combos our team uses in web development.

Just drop us a line if you need any help with React integration.

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

Share:

Subscribe
Notify of
guest

5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Recommended articles
#Tech 7 min

In the fight of two’s, only one can win.  Who would it be: PHP or Ruby? Ruby and PHP programming languages have been competitors since day one of their first appearances. Since then, the fight…

#Tech 13 min

Did you know an app that loads in 1 second has a conversion rate 3x higher than a site that loads in 5 seconds? This goes to show application speed and performance are crucial for…

#Tech 8 min

  Web scraping is a popular method of automatically collecting the information from different websites. It allows you to quickly obtain the data without the necessity to browse through the numerous pages and copy and…

Scale your team with us

Drive your business with our dedicated developers