DEV Community

Cover image for A Simple Guide: Integrating Rails Backend with React Frontend
Leonel Oliveira
Leonel Oliveira

Posted on

A Simple Guide: Integrating Rails Backend with React Frontend

Rails is a powerful framework for building web applications, known for its MVC pattern and numerous gems that simplify development. However, when it comes to frontend development, some developers prefer using React for its flexibility and rich ecosystem. In this article, we'll explore two ways to configure a Rails backend with a React frontend.

API Only Option:

To create a Rails API-only application, use the following command:

rails new <name_of_your_app> --database=postgresql --api -T
Enter fullscreen mode Exit fullscreen mode

This command sets up a Rails app without views, using PostgreSQL as the database and skipping unnecessary assets and sessions. You can then add a .env file for database credentials and configure the database accordingly.

Next, you can scaffold a User model for testing purposes:

rails g scaffold User
rails db:create
rails db:migrate
rails s -p 3001
Enter fullscreen mode Exit fullscreen mode

Frontend Setup:

For the frontend, generate a React app using:

npx create-react-app <your_app_name>
Enter fullscreen mode Exit fullscreen mode

Configure your React app as needed, adding dependencies like Redux, Axios, and Bootstrap:

yarn add redux react-redux axios bootstrap
Enter fullscreen mode Exit fullscreen mode

You can then make API requests from your React components using Axios. For example:

axios.get('http://localhost:3001/users').then(response => console.log(response.data))
Enter fullscreen mode Exit fullscreen mode

Configuring Rails with Webpacker:

To integrate React into a full Rails app, use the following command:

rails new <your_app_name> -d=postgresql -T --webpack=react --skip-coffee
Enter fullscreen mode Exit fullscreen mode

This command sets up a Rails app with React configured with Webpacker. You can scaffold a User model, set up the database, and run the server as before.

In your React components, you can then include the React pack tag in your views to connect the frontend with the backend:

<%= javascript_pack_tag 'hello_react' %>
Enter fullscreen mode Exit fullscreen mode

Finally, update your routes.rb file to route to the React frontend:

root 'users#index'
Enter fullscreen mode Exit fullscreen mode

With these steps, you can effectively integrate a Rails backend with a React frontend, allowing for a seamless development experience.

Happy coding! 🚀

Top comments (0)