A Simple Guide to Integrating Rails Backend with React Frontend

RMAG news

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

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

Frontend Setup:

For the frontend, generate a React app using:

npx create-react-app <your_app_name>

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

yarn add redux react-redux axios bootstrap

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))

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

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’ %>

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

root ‘users#index’

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

Happy coding! 🚀

Leave a Reply

Your email address will not be published. Required fields are marked *