DEV Community

Cover image for Building a Modern Rails App with React and Vite: A Complete Guide
Arunkumar
Arunkumar

Posted on

Building a Modern Rails App with React and Vite: A Complete Guide

The evolution of front-end tooling has significantly enhanced the developer experience. Vite, known for its lightning-fast build tool and hot module replacement, now integrates seamlessly with Ruby on Rails via the vite_rails gem. Gone are the days of slow webpack builds โ€“ with Vite, you get instant feedback and blazing-fast development cycles.

In this comprehensive guide, we'll walk through setting up a modern Rails application with React using Vite, creating a powerful full-stack development environment.

Prerequisites

Before we begin, ensure you have the following installed:

  • Ruby (3.0+)
  • Rails (7.0+)
  • Node.js (16+)
  • npm or yarn

Step 1: Create a New Rails Application

First, let's create a fresh Rails project:

rails new rails_react_app --skip-javascript
cd rails_react_app
Enter fullscreen mode Exit fullscreen mode

Note: We use --skip-javascript to avoid conflicts with Rails' default JavaScript setup since we'll be using Vite.

Step 2: Add Vite Rails

Add the vite_rails gem to your Gemfile:

# Gemfile
gem 'vite_rails'
Enter fullscreen mode Exit fullscreen mode

Install the gem and set up Vite:

bundle install
bundle exec vite install
Enter fullscreen mode Exit fullscreen mode

This command will:

  • Generate package.json with Vite dependencies
  • Create vite.config.ts configuration file
  • Set up the app/frontend/entrypoints/ directory (default location for JS entrypoints)
  • Configure Rails to work with Vite

For more details, check the official guide: vite-ruby.netlify.app/guide/

Step 3: Install React Dependencies

Install React and its dependencies using npm:

npm install react react-dom @vitejs/plugin-react
Enter fullscreen mode Exit fullscreen mode

Update your vite.config.ts to include the React plugin:

// vite.config.ts
import { defineConfig } from 'vite'
import RubyPlugin from 'vite-plugin-ruby'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [
    RubyPlugin(),
    react(),
  ],
})
Enter fullscreen mode Exit fullscreen mode

Step 4: Create Your React Application Structure

Let's organize our code properly. Create the necessary directories and files:

mkdir -p app/frontend/src/components
touch app/frontend/entrypoints/application.jsx
Enter fullscreen mode Exit fullscreen mode

Create the main React component:

// app/frontend/src/App.jsx
import React from 'react';

const App = () => {
  return (
    <div className="container mx-auto p-8">
      <h1 className="text-4xl font-bold text-blue-600">
        Hello from Rails + React + Vite! ๐Ÿš€
      </h1>
      <p className="mt-4 text-gray-600">
        Your modern full-stack development environment is ready!
      </p>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Create a sample component:

// app/frontend/src/components/Welcome.jsx
import React from 'react';

const Welcome = ({ message }) => {
  return (
    <div className="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded">
      <p>{message}</p>
    </div>
  );
};

export default Welcome;
Enter fullscreen mode Exit fullscreen mode

Step 5: Set Up Your Application Entrypoint

Update your entrypoint file to render the React app:

// app/frontend/entrypoints/application.jsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from '../src/App';

// Import CSS if you're using any
import './application.css';

document.addEventListener('DOMContentLoaded', () => {
  const rootElement = document.getElementById('root');

  if (rootElement) {
    const root = createRoot(rootElement);
    root.render(<App />);
  }
});
Enter fullscreen mode Exit fullscreen mode

Step 6: Update Your Rails Layout

Modify your application layout to include Vite assets and provide a mount point for React:

<!-- app/views/layouts/application.html.erb -->
<!DOCTYPE html>
<html>
  <head>
    <title>Rails React App</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= vite_client_tag %>
    <%= vite_stylesheet_tag 'application' %>
  </head>

  <body>
    <div id="root"></div>
    <%= yield %>

    <%= vite_javascript_tag 'application' %>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 7: Create a Controller and Route

Generate a controller to serve your React app:

rails generate controller Pages index
Enter fullscreen mode Exit fullscreen mode

Update the controller:

# app/controllers/pages_controller.rb
class PagesController < ApplicationController
  def index
    # This will render the view where React will mount
  end
end
Enter fullscreen mode Exit fullscreen mode

Set up your routes:

# config/routes.rb
Rails.application.routes.draw do
  root 'pages#index'
  get 'pages/index'
end
Enter fullscreen mode Exit fullscreen mode

Create the view (it can be minimal since React handles the UI):

<!-- app/views/pages/index.html.erb -->
<!-- React will mount here via the #root div in the layout -->
Enter fullscreen mode Exit fullscreen mode

Step 8: Start Your Development Servers

Now you can start both Rails and Vite in development mode:

Terminal 1 - Rails server:

rails server
Enter fullscreen mode Exit fullscreen mode

Terminal 2 - Vite dev server:

bin/vite dev
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can use a process manager like foreman. Create a Procfile.dev:

web: rails server -p 3000
vite: bin/vite dev
Enter fullscreen mode Exit fullscreen mode

Then run:

foreman start -f Procfile.dev
Enter fullscreen mode Exit fullscreen mode

Key Benefits of This Setup

  1. โšก Lightning Fast: Vite's hot module replacement provides instant feedback
  2. ๐Ÿ”ง Modern Tooling: ES modules, TypeScript support out of the box
  3. ๐Ÿ“ฆ Optimized Builds: Vite creates highly optimized production bundles
  4. ๐ŸŽฏ Rails Integration: Seamless integration with Rails asset pipeline
  5. ๐Ÿ› ๏ธ Developer Experience: Excellent debugging and development tools

Production Deployment

For production deployment, Vite will automatically build optimized assets. Make sure to:

  1. Add the build step to your deployment process:
   bundle exec vite build
Enter fullscreen mode Exit fullscreen mode
  1. Ensure your production environment serves static assets properly

Troubleshooting Common Issues

Issue: React not mounting

  • Ensure the #root div exists in your layout
  • Check browser console for JavaScript errors
  • Verify Vite dev server is running

Issue: Assets not loading

  • Confirm vite_client_tag and vite_javascript_tag are in your layout
  • Check that Vite configuration is correct
  • Ensure all dependencies are installed

Issue: Hot reload not working

  • Restart the Vite dev server
  • Check for syntax errors in your React components
  • Verify your Vite configuration includes the React plugin

Conclusion

You now have a powerful, modern Rails application with React and Vite! This setup provides:

  • Instant hot module replacement for rapid development
  • Optimized production builds
  • Modern JavaScript tooling
  • Seamless Rails integration

The combination of Rails' robust backend capabilities with React's dynamic frontend and Vite's exceptional developer experience creates an ideal environment for building modern web applications.

Happy coding! ๐Ÿš€


For more advanced configurations and deployment strategies, check out the Vite Ruby documentation and React documentation.

Top comments (0)