Complete Guide: How to Build a SPA with Rails and React

programming

Are you worried about combining Rails and React to develop a SPA (single page application), but not sure how to go about doing it?

In this article, we will clearly explain how to build an SPA by integrating Rails and React, from setting up the environment to basic implementation.

How Rails and React work together

There are three main ways to integrate Rails and React:

1. Incorporating React components into Rails views

The react-rails gem allows you to include React components directly in your Rails views.

2. Use Rails as an API server and React as a separate frontend

This method involves building Rails as a backend dedicated to the API, and building the frontend using React as a separate project.

3. Using React on Rails

Here's how to integrate Rails with React using the react_on_rails gem.

In this article, we will use the second approach, which is to use Rails as an API server and React as a separate front-end.

Environment setup procedure

Prerequisites

• Ruby 3.1 or later

• Rails 7.0 or higher

• Node.js 16 or higher

• Yarn  

Creating the Rails API

1

CORS Settings

Create config/initializers/cors.rb and add the following content:

1
0 '' '*', , , , , ,

Creating a React App

1

Creating a React component and incorporating it into Rails

Create components with React and communicate with the Rails API to retrieve and display data.

Example: Displaying a list of users

frontend/src/components/UserList.js

1
2
3
4
5
6
7
8
9
10
    <>
      <>
      <>
        
          < =>
        ))}
      </>
    </>
  

Implementing SPA Routing

We will use React Router to implement client-side routing.

Routing Configuration

frontend/src/App.js

1
=

Communicating with the API and retrieving data

We'll create an API endpoint on the Rails side and retrieve the data from React.

Creating a Rails Controller

1

app/controllers/api/users_controller.rb 

Routing Configuration

config/routes.rb 

1
]

summary

In this article, we explained how to build an SPA by integrating Rails and React.

• Building Rails as an API server

• Building the frontend with React

• CORS configuration

• Routing with React Router

• Communicating with the API using Axios 

This configuration allows the front-end and back-end to be separated and developed and maintained independently.

In the future, consider further expanding the functionality, such as adding authentication functionality or introducing a state management library (e.g. Redux).

Copied title and URL