React With Ruby on Rails – React Frontend and Ruby on Rails Backend

Quick Summary: Wondering how to combine React and Ruby on Rails? Ruby on Rails and React are leading technologies in their domains – server-side and client-side development. They are often used together to create meaningful full-stack web app projects. However, is it suitable for your web app project? Here is everything you need to know about React Ruby on Rails combination.

Most of our clients generally ask for Ruby on Rails developers to power the backend of their app. And although in the earlier years, more clients preferred Angular to power their frontend, we have seen a drastic shift towards React. Even if you know the market trends, for instance, from SimilarTech, you can see that Angular only powers 347,372 websites, whereas 1,237,495 websites currently use React JS. Massive difference.

However, each project has a different requirement, and all frameworks have certain advantages and disadvantages over each other. But since we decided to use Ruby on Rails backend with React frontend, let us see how we should go about it and the various benefits and limitations of this approach.

Understanding Ruby on Rails and React in Greater Detail

Let’s start by understanding Ruby on Rails and React as individual platforms and then move on to why these frameworks work so well together.

Why Should You Use Ruby on Rails For The Backend?

So, what is Ruby on Rails? It is one of the most popular backend frameworks in the market today that is used for developing API-driven backend solutions for modern apps.

Why Use Ruby on Rails for The Backend?

One of the many reasons for Ruby on Rails popularity as a backend service is its extensive list of ready-made solutions for repetitive and essential tasks. Moreover, it seamlessly integrates with frameworks based on other programming languages, such as HTML, CSS, and JavaScript. You can incorporate any popular frontend technology with Rails as the backend; however, the most popular options are Vue/React.

Also Read : 8 Spectacular Benefits of Using Ruby on Rails for Web Development

Why Should You Use React for The Frontend?

React is a popular JavaScript frontend framework that handles the Views in the Model Views Controller architecture for client-side user interfaces.

Why Use React for The Frontend?

Frontend development using React is not only easy to grasp but also one of the most structured and efficient frontend frameworks with out-of-the-box support for component-based architecture, Virtual DOM, and various state management approaches.

LookinG for React developers to hire?

Get in touch to develop highly scalable web app project.

Why Use Ruby on Rails With React?

So, what makes Ruby on Rails and React a perfect match? Using React with Ruby on Rails is very easy, and there are many ways to integrate the two platforms. Moreover, combining React with Ruby on Rails has many benefits over other full-stack solutions. Here are some of the top reasons for combining React with Ruby on Rails:

Why Use Ruby on Rails With React?

Faster Time to Market

Ruby on Rails has a vast repository of plugins, tools, and apps, as well as out-of-the-box models and coding libraries, helping developers develop your project faster and work efficiently with React components. This helps reduce many development hours that would go under setting up mundane and repetitive tasks, reducing the overall development time and, subsequently, costs.

Reliability and Stability

Ruby on Rails and React are established frameworks that have proven their worth over time with active communities and constant support for updates, maintenance, and industry-grade features to keep up with the development advancements. Hence, choosing React with Ruby on Rails will assure you of a stable environment and scalable app solution. Moreover, this combination is used by leading global companies such as Twitter, Crunchbase, AirBnB, and GitHub.

Memory Usage Optimization

Combining Ruby on Rails and React helps reduce memory consumption and usage by optimizing the utilization of resources and reducing the overall line of codes, keeping the app bug free and less prone to downtimes.

Reduction in Server Request Time

Server response plays a significant role in the overall app experience for a customer. Faster response time leads to faster page/app loading and making content available for users in no time. This keeps the user interested in browsing your services and spending more time on your app. It helps them get their tasks done quickly and effortlessly. Ruby on Rails combined with React enables you to optimize your project’s server request time significantly.

When to Use React with Ruby on Rails: Use Cases

If you are sure about using React with Ruby on Rails, you can skip to the ‘How to set up a Ruby on Rails React Project’ section below. If you are still not sure if Ruby on Rails with React is the right choice for your business, here are some of the top use cases and industries where combining React with Ruby on Rails is an ideal choice:

When to use React with Ruby on Rails?

Dynamic Apps

If your app requires to be connected to an online server or a database and the data presented on your app is bound to change frequently, you are looking to build a dynamic app project. A vibrant app needs to be responsive, consistent, and highly engaging. Ruby on Rails can handle the responsiveness and performance aspects of your active app. In contrast, React has many UI libraries and component-based development systems to make highly interactive and appealing frontends for your dynamic app.

Single Page Applications

Single Page Applications are web apps that display all the relevant information and contents of the site on a single page with dynamic sections and components. The idea is to provide an easily navigable web experience to the users. Since Ruby can improve the overall speed of applications by reducing the loading time of JS, HTML, and CSS files, it makes the Single Page Application experience seamless and highly performant.

Moreover, React is one of the most popular frontend frameworks for developing Single Page Applications due to its UI component-driven development approach and features like client-side and server- side rendering.

Mobile Applications Using React Native Ruby on Rails

If you need a comprehensive solution for your project, choosing React Ruby on Rails can be ideal. Using Ruby on Rails + React can help you develop robust web solutions. Similarly, using React Native and Ruby on Rails is ideal for mobile app development.

React Native is one of the leading cross-platform app development frameworks that allow coders to reuse almost upto 90% of their code between Android and iOS platforms. And Ruby on Rails works 30-40% faster than any other backend framework. Combined, they can significantly reduce your app development costs while enabling you to build a secure and robust app.

How to Setup Ruby on Rails with React: Prerequisites

Now that we understand the various benefits and use cases of integrating React Ruby on Rails, we can start building a Ruby on Rails with React project. However, before we get into the how-to, we should clarify the prerequisites to be configured/installed before starting the project. If you already know the prerequisites, you can skip to the ‘How to setup Ruby on Rails with React: The Process’ section.

Prerequisites of Setting Up React Ruby on Rails project:

  • Ruby on Rails installed
  • NPM and Node.js installed
  • Heroku CLI installed
  • VS Code or any other text editor
  • A web browser, ideally Chrome or Firefox
  • Developers who are proficient in React, Ruby on Rails, JS, Axios, and Heroku CLI
  • Yarn Package Manager

Different Approaches on How to setup Ruby on Rails with React

There are two proper approaches to setting up React with Ruby on Rails – Using Rails API or using the Rails GEM approach. API configuration was added in Ruby on Rails 5, and Ruby on Rails version 6 provided developers with the ease of building React apps on Rails with webpack. All three approaches have their limitations and benefits. Let’s understand them better:

How to setup Ruby on Rails with React?

1. Setting Up React with Ruby on Rails API

This is one of the most popular approaches that most developers prefer. It makes sense if you want to set up a mobile application in the near future. With API-driven development, you could set up your Ruby on Rails backend with React Native frontend to set up the cross-platform mobile app development process by making JSON/XML requests to the server.

In this method, we want to create two standalone applications. One of the applications will handle databases and other backend functionalities (Ruby on Rails, in our case). And after we set up this application, we will create the other application for handling the front end of our project (React.js in our case).

Hence Your Basic Project Structure Should Look Like This:

  • my_application
  • front_end
  • back_end

The reason for setting up a standalone React web app at first instead of directly using a Ruby on Rails API application is to save up time setting up different libraries that we would have to if we followed that approach. Now the React app will retrieve all data via a server request. Once you set up your React Ruby on Rails project this way, you will have the web app running on the same parent address but on different ports.

Ruby on Rails, for instance, can be hosted on localhost:3000, and the React app can be hosted on localhost:4000 where the local host address is the same, for example, 127.0.0.1:3000 and 127.0.0.1:4000. Since the address is same, the response of our Ruby on Rails with React app will be faster.

How to Develop a React With Ruby on Rails API Project:

Now that we understand how the API method works let’s see it in action!

Setting Up the React Client

Start by opening your terminal to the location where you want to deploy your project and make a directory for holding Ruby on Rails backend with React frontend. Run the following commands :

mkdir new-project

cd new-project

Now for using React on the frontend, add the following code:

npx create-react-app new-project-client

Now open the folder with this project and change the directory to your New React App

code.
cd new-project-client

Once you are done with these steps, connect your React code to a GitHub repository. When you typed the command ‘create-react-app,’ it would have initialized a GIT repository. Check if it already exists; if not, you can add it manually using this command:

git init

After initializing your GitHub repository, log in to your GitHub account and click the ‘New Repository’ button located on the “+” icon next to the notification bell icon on the top right corner. This will open up the ‘Create a Repository Page’ where you can name your project. You will also get an option to initialize your Github repository here but refrain from doing so as we already did in the previous stage. Once you have named the repository, press the ‘Create Repository’ button.

Next, run the following commands in the terminal:

git remote add origin [email protected]:MMcClure11/new-project-client.gitgit push

We are now done setting up the frontend of our React with Ruby on Rails API project. Let’s move on to setting the backend with Rails API.

Creating Rails API

After working on the React client app, you first need to cd out of the client directory, so you start working on the folder responsible for holding both frontend and backend projects. Start by adding the following command on the terminal :

cd ..

To create a Rails app, we need to add the API flag and mention PostgreSQL as a database if you use Heroku CLI. Add the following code:

rails new new-reactrails-api --api --database=postgresql

Now we make an initial GitHub commit for setting up a Rails API GitHub repository:

git init

git add .

git commit -m "Initial commit."

After this is done, run the following code on the terminal :

git remote add origin [email protected]:MMcClure11/new-project-api.gitgit push

Next, you need to add your preferred Active Model Serializer that will help create custom JSON in an object-oriented manner.

bundle add active_model_serializers

Now you need to remove the rack-cors gem to allow the React frontend to establish a connection with our Rails backend.

gem 'rack-cors'

Next, run the following code on the terminal:

bundle install

After this, we will navigate to the config/initializers/cors.rb directory and add a comment for using cors middleware.

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://localhost:3000', 'http://localhost:3001', 'http://localhost:3002'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

And you’re good to go! This is how you can develop a React with Ruby on Rails project using Rails API with React client-side app.

2.The React-Rails GEM Method

Rails offer extensive libraries in the name of ‘Gems’ that allow Ruby on Rails developers to add certain necessary functionalities without having to write the code to achieve its result. It helps enable a feature without repeating the code again and again. Since Ruby on Rails with React has such a massive popularity, there is an official React gem library known as React-Rails that uses the react_component helper method, which establishes communication between Rails data and its components. React-rails can be used with webpacker.

How to Develop a React-Rails Project?

Let’s get to the coding portion of how to develop a React-Rails project with webpacker! Here is your React Ruby on Rails tutorial:

Step 1: Create a Rails Project with React and Webpack

Name your Rails app at your convenience and create a new project.

rails new react-app --webpack=react

Note: Ensure to update your app to Rails 6 before starting this process.

Step 2: Ensure Your React-Rails and Webpacker Gems are Rightly Installed

Go to your Gemfile and check if the React-Rails and Webpacker gems are present. If not, then you need to add them manually by copying the following code into the Gemfilefolder:

# Webpack and React
gem ‘webpacker’
gem ‘react-rails’ 
# Bundle edge Rails instead: gem ‘rails’ , github: ‘rails/rails’
gem ‘rails’, ‘~> 5.2.1’

Now to install both React webpacker and React-Rails gems, use the following command

$ bundle install

Once the bundle gets installed, run the following react-rails installation script by using a Rails generator :

$ rails generate react:install or rails g react:instal
      create  app/assets/javascripts/components
      create  app/assets/javascripts/components/.keep
      insert  app/assets/javascripts/application.js
      create  app/assets/javascripts/components.js
      create  app/assets/javascripts/server_rendering.js
      create  config/initializers/react_server_rendering.rb

Doing so will create a components directory under your apps/assets/javascripts directory alongside a manifest file. This will be added to our application.js file. Hence now we can add React components in our React-rails app under the apps/assets/javascripts/components directory. We can save this directory with a JSX extension.

Step 3: Creating React Components

Let’s create a React component called ‘Articles’ for our example. First, to create our component, we write the following code:

$  rails g react:component articles

create  app/assets/javascripts/components/articles.js.jsx

Now under the sub-component articles.js.jsx add this code snippet :

var Articles = createReactClass({
  propTypes: {
    articles: [
      {
        title: PropTypes.string,
        author: PropTypes.string
      }
    ]
  },
  render: function() {
    return (
      <table>
        <thead>
          <tr>
            <th>Title</th>
            <th>Author</th>
          </tr>
        </thead>
        <tbody>
          {this.props.articles.map(article => (
            <tr key={article.title}>
              <td>{article.title}</td>
              <td>{article.author}</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }
});

After this, we can render the React component in Rails like the following :

<%= react_component("Articles", articles: [ { title: "Ruby on Rails", author: "Aglowid" }, { title: "Tutorial", author: "Ronak"}]) %>

Wrapping up!

This is your ultimate guide on setting up React Ruby on Rails project and its benefits, use cases, and other considerations. Make sure your project benefits from leveraging this full-stack development duo and consult with an established ReactJS Development Company to better understand better how to combine React and Ruby on Rails to power your project as cost-effectively and efficiently as possible.

have a unique app Idea?

Hire Certified Developers To Build Robust Feature, Rich App And Websites

Need Consultation?

Put down your query here...

    Saurabh Barot

    Saurabh Barot, the CTO of Aglowid IT Solutions, leads a team of 50+ IT experts across various domains. He excels in web, mobile, IoT, AI/ML, and emerging tech. Saurabh's technical prowess is underscored by his contributions to Agile, Scrum, and Sprint-based milestones. His guidance as a CTO ensures remote teams achieve project success with precision and technical excellence.

    Related Posts