DEV Community

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

Posted on

A Simple Guide to Integrating Rails Backend with React Frontend

Rails is a powerful framework known for its MVC pattern and numerous gems that simplify web application development. However, for frontend development, many developers prefer using React due to its flexibility and rich ecosystem. In this guide, we'll explore how to seamlessly integrate a Rails backend with a React frontend, including how to populate the database with user data.

Setting Up the Backend:

API-Only Configuration:

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. Create a .env file for database credentials and configure the database accordingly.

Next, 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

Populating the Database:

Rails provides a way to populate the database with initial data using seed files. Create a new seed file db/seeds.rb with the data you want to populate. For example:

   # db/seeds.rb
   User.create(name: 'John Doe', email: 'john@example.com')
   User.create(name: 'Jane Doe', email: 'jane@example.com')
Enter fullscreen mode Exit fullscreen mode

Run the seed file using the following command:

   rails db:seed
Enter fullscreen mode Exit fullscreen mode

This command executes the code in the seeds.rb file and populates the database with the specified data.

Setting Up the Frontend:

Creating the React App:

Generate a React app in a separate directory 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

Fetching and Displaying Data:

Update your React components to fetch and display the user data. Modify your UsersList component to fetch the users from the backend:

   import React, { useState, useEffect } from 'react';
   import axios from 'axios';

   const UsersList = () => {
     const [users, setUsers] = useState([]);

     useEffect(() => {
       axios.get('http://localhost:3001/users')
         .then(response => {
           setUsers(response.data);
         })
         .catch(error => {
           console.error('Error fetching users:', error);
         });
     }, []);

     return (
       <div>
         <h1>Users List</h1>
         <ul>
           {users.map(user => (
             <li key={user.id}>{user.name}</li>
           ))}
         </ul>
       </div>
     );
   };

   export default UsersList;
Enter fullscreen mode Exit fullscreen mode

Adding Users from Frontend:

Create a form in your React frontend to collect user information and send a POST request to the backend to create a new user. Implement the form submit handler:

   const handleSubmit = (event) => {
     event.preventDefault();

     axios.post('http://localhost:3001/users', { name, email })
       .then(response => {
         console.log('User created successfully:', response.data);
         // Clear the form
         setName('');
         setEmail('');
       })
       .catch(error => {
         console.error('Error creating user:', error);
       });
   };
Enter fullscreen mode Exit fullscreen mode

This form should be connected to the handleSubmit function and update the state with the new user data.

Conclusion:

By following these steps, you can effectively integrate a Rails backend with a React frontend, populate the database with user data, and create a seamless development experience.

Happy coding! 🚀

Top comments (0)