Setting Up React with Rails API

Aug 22, 2024

Using React with Rails: Introduction and Setup

Introduction

  • React as the frontend, Rails as the backend API.
  • Despite trends (e.g., Hotwire), React with Rails is still relevant in the industry.
  • Useful for interviews and new tech stacks.
  • Series will evolve over time; this is just the beginning.

Initial Project Description

  • Building a simple CRUD app.
  • Posts can be created, edited, and deleted.
  • Rails serves as the backend, React communicates via API.

Overhead and Company Decisions

  • Communication between React (frontend) and Rails (backend) incurs overhead.
  • Companies may choose React for its rich ecosystem and available talent.

Setup and Project Creation

Rails API Setup

  • Navigate out of Rails app and create a new Rails API project:
    rails new video --api
    
  • This creates controllers and models without views.

File Structure

  • Traditional Rails app structure minus view files.
  • Important files: routes.rb, gemfile, controllers, initializers.

Configure CORS (Cross-Origin Resource Sharing)

  • Un-comment rack-cors gem in Gemfile, then run bundle install.
  • In config/initializers/cors.rb, un-comment and configure origins.
    • Example: Use the local server IP (127.0.0.1:5173) during development.
    • In production, specify a domain.

Scaffold Setup

  • Generate scaffold for Post:
    rails g scaffold Post title:string body:text
    
  • Note: No views generated due to API-only flag.

Seeding Database

  • Add faker gem for test data generation.
  • Create seed data in db/seeds.rb using Faker:
    Post.destroy_all
    20.times do
      Post.create(title: Faker::Lorem.sentence(word_count: 3), body: Faker::Lorem.paragraph(sentence_count: 3))
    end
    
  • Migrate and seed database:
    rails db:migrate
    rails db:seed
    

Ordering Posts

  • Order posts by creation date in descending order in controller:
    Post.order(created_at: :desc)
    

Testing and Version Control

Testing

  • Use Rails test framework to ensure functionality.
  • Add rails-controller-testing gem to support certain test methods.
  • Example test: Check if posts are ordered correctly.

Version Control

  • Initialize git and commit changes:
    git add .
    git commit -m 'Initial commit'
    
  • Create a GitHub repository and push changes to remote.

Conclusion

  • Part one of the series covers setting up a Rails API for use with React.
  • Future videos will expand upon this foundation.
  • Series aims to prepare viewers for professional use cases and interviews.