This app works best with JavaScript enabled.
Getting Started
Overview
What is React on Rails?
Why React on Rails?
When to Use React on Rails
Getting Started
🚀 New to React on Rails?
📦 Adding to an Existing Rails App?
📚 Want a Comprehensive Tutorial?
👀 Learn by Example?
Popular Use Cases
Core Concepts
Philosophy
System Requirements
Need Help?
Community Support
Professional Support
External Resources
Quick Start
✅ Prerequisites
📦 Step 1: Install React on Rails (3 minutes)
🎯 Step 2: Start the Development Server (1 minute)
🎨 Step 3: See Your Component (2 minutes)
🔧 Step 4: Edit Your Component (2 minutes)
🚀 Step 5: Add Components to Existing Views (5 minutes)
Create a New Component
Use It in a Rails View (Auto-Bundling)
✅ What You've Accomplished
🎓 Next Steps
Immediate Next Steps
Dive Deeper
Advanced Features
🆘 Need Help?
📋 Quick Reference
Essential Commands
Key File Locations
Installation Into An Existing Rails App
Installation
NPM
Tutorial
Table of Contents
Installation
Setting up your environment
Create a new Ruby on Rails App
Add the Shakapacker and react_on_rails gems
Run the Shakapacker generator
Run the React on Rails Generator
Setting up your environment variables
Running the app
HMR vs. React Hot Reloading
Deployment
Going Further
Turning on Server Rendering
Optional Configuration
Moving from the Rails default /app/javascript to the recommended /client structure
Custom IP & PORT setup (Cloud9 example)
RubyMine performance tip
Conclusion
Using React On Rails
Installation Overview
Using React Components in Rails Views
Basic Options
Configuration
Auto-Bundling and Component Registration
Traditional Manual Registration
Modern Auto-Bundling (Recommended)
Understanding What the Generator Creates
Component Structure
Rails Integration
Webpack Configuration
Development Workflow
Render-Functions and RailsContext
Basic Example
When to Use Render-Functions
Server-Side Rendering with Render-Functions
Error Handling
Next Steps
Build Features
Deploy to Production
Advanced Topics
API Reference
Project Structure
Modern Auto-Bundling Structure (Recommended)
Traditional Manual Structure (Legacy)
Choosing Your Structure
Steps to convert from the generator defaults to use a /client directory for source code
Styling Your Components
Modern Approach: CSS Modules (Recommended)
Alternative: Rails Asset Pipeline
Advanced: Global Styles with Webpack
Core Concepts
How React On Rails Works
Client-Side Rendering vs. Server-Side Rendering
HTML Source Code
Building the Bundles
Client Vs Server Rendering
Render Functions
Types of Render-Functions and Their Return Values
Identifying Render-Functions
1. React Components
2. Objects with renderedHtml string property
3. Objects with renderedHtml as object containing componentHtml and other properties if needed (server-side hash)
4. Promises of Strings
5. Promises of server-side hash
6. Promises of React Components
7. Redirect Information
Important Rendering Behavior
Ruby Helper Functions
1. react_component
When to use
Not suitable for
2. react_component_hash
When to use
Not suitable for
Requirements
Examples with Appropriate Helper Methods
Return Type 1: React Component
Return Type 2: Object with renderedHtml
Return Type 3: Object with server-side hash
Return Type 4: Promise of String
Return Type 5: Promise of server-side hash
Return Type 6: Promise of React Component
Return Type 7: Redirect Object
Render Functions And Railscontext
Render-Functions
Rails Context
Why is the railsContext only passed to render-functions?
Use Cases
Heroku Preboot Considerations
Needing the current URL path for server rendering
Configuring different code for server side rendering
Customization of the Rails context
React Server Rendering
What is the easiest way to set up a Webpack configuration for server-side-rendering?
What is Server Rendering?
How do you do Server Rendering with React on Rails?
Do you need server rendering?
Considerations for what code can run on in server rendering
Auto Bundling File System Based Automated Bundle Generation
Configuration
Enable nested_entries for Shakapacker
Configure Components Subdirectory
Configure auto_load_bundle Option
Location of generated files
Update .gitignore file
Commit changes to server bundle entrypoint
Usage
Basic usage
Background
Solution
Layout Integration with Auto-Loading
Complete Working Example
1. Configure Shakapacker
2. Configure React on Rails
3. Directory Structure
4. Component Implementation
5. Rails Layout
6. Rails Views and Controller
7. Generate Bundles
8. Update .gitignore
9. Start the Server
Performance Screenshots
Server Rendering and Client Rendering Components
Using Automated Bundle Generation Feature with already defined packs
Troubleshooting
Common Issues and Solutions
1. "Component not found" errors
2. CSS not loading (FOUC - Flash of Unstyled Content)
3. "document is not defined" errors during SSR
4. Bundles not being generated
5. Manual pack tags not working after switching to auto-loading
6. Bundle size issues
7. Development vs Production differences
Debug Mode
Webpack Configuration
Webpack vs. Shakapacker
Option 1: Default Generator Setup: Shakapacker app/javascript
Option 2: Traditional React on Rails using the /client directory
Building Features
Hmr And Hot Reloading With The Webpack Dev Server
Server Side Rendering with the Default shakacode/shakapacker bin/shakapacker-dev-server
If you use the same Webpack setup for your server and client bundles
Client-Side rendering with HMR using react-refresh-webpack-plugin
Basic installation
React Router
Compatibility Note
Installation
Basic Client-Side Setup with Redux
Server-Side Rendering with React Router
Rails Routes Configuration
Example Application
Additional Resources
React And Redux
Communication Between Components
Redux Reducers
I18n
Notes
Images
React Helmet
Installation and general usage
Example
Rspec Configuration
If your Webpack configurations correspond to Shakapacker's default setup
Checking for stale assets using React on Rails
Minitest Configuration
Streaming Server Rendering
Prerequisites
Benefits of Streaming Server Rendering
Implementation Steps
When to Use Streaming
Ideal Use Cases
Best Practices for Streaming
How To Conditionally Server Render Based On Device Type
config/initializers/react_on_rails.rb
How To Use Different Files For Client And Server Rendering
How to use different versions of a file for client and server rendering
A. Using different Entry Points
B. Two Options for Using Webpack Resolve Alias in the Webpack Config
1. Update webpack/set-resolve.js to have a different resolution for the exact file
2. Use a different resolution for the right directory of client or server files
a. Update webpack/set-resolve.js to have something like
b. Add different versions of the file to the bundles/variant/ClientOnly and bundles/variant/ServerOnly directories
c. Use the variant in import in a file that can be used both for client and server rendering
C. Conditional code that can check if window is defined.
Rails Webpacker React Integration Options
Suppress warning related to Can't resolve 'react-dom/client' in React < 18
HMR and React Hot Reloading
React Refresh Webpack Plugin
React Hot Loader (Deprecated)
Turbolinks
React on Rails Updated to support Turbo, August 2024
Using Turbo
Legacy Turbolinks Support
Why Turbolinks?
Requirements for Using Turbolinks
Why Not Turbolinks
Installation
Install Checklist
Turbolinks from NPM
Async script loading
Turbolinks 5 Specific Information
Technical Details and Troubleshooting
CSRF and MIME Type Handling
Debugging Turbolinks Events
Process Managers
Running Your Development Server
Installing a Process Manager
Overmind (Recommended)
Foreman (Alternative)
Alternative: Run Process Managers Directly
Customizing Your Setup
See Also
API Reference
View Helpers Api
View Helpers API
react_component
react_component_hash
cached_react_component and cached_react_component_hash
rails_context
Renderer Functions (function that will call ReactDOM.render or ReactDOM.hydrate)
React Router
server_render_js
More details
Javascript Api
CSRF protection
API
Configuration
Redux Store Api
Multiple React Components on a Page with One Store
Controller Extension
View Helper
More Details
Generator Details
Understanding the Organization of the Generated Client Code
Default Structure (Without Redux)
Redux Structure (With --redux Option)
TypeScript Support
Auto-Bundling and Component Registration
Rails View Rendering From Inline Javascript
Why do we need this?
Deployment
Deployment
Heroku Deployment
Create Your Heroku App
Heroku buildpacks
Swap out sqlite for postgres
Configure Puma
Specify Node and Yarn versions
Deploy
assets:precompile
Shakapacker Webpack configuration
Consider Removing Shakapacker's clean task
Capistrano Deployment
Elastic Beanstalk
Server Rendering Tips
General Tips
Troubleshooting Server Rendering
CSS
setTimeout, setInterval, and clearTimeout
Troubleshooting
🔍 Quick Diagnosis
Is your issue with...?
🚨 Installation Issues
"Generator fails with uncommitted changes"
"Node/Yarn not found"
🔧 Build Issues
"Module not found: Can't resolve 'react-on-rails'"
"Webpack compilation failed"
"ExecJS::RuntimeUnavailable"
⚡ Runtime Issues
"Component not rendering"
"ReferenceError: window is not defined"
"Props not updating"
"Flash of Unstyled Content (FOUC)"
🖥️ Server-Side Rendering Issues
"Server rendering not working"
"Hydration mismatch warnings"
🐌 Performance Issues
"Slow webpack builds"
"Large bundle sizes"
🛠️ Advanced Debugging
Enable verbose logging
Debug webpack configuration
Check component registration
🆘 Still Stuck?
Before asking for help, gather this info
Get community help
Professional support
Troubleshooting Build Errors
Table of Contents
Missing Routes File Error (js-routes gem)
Error Message
Root Cause
When You Need js-routes
When You DON'T Need js-routes
Solution (if using js-routes)
Alternative Solution (if NOT using js-routes)
ProvidePlugin Module Resolution Errors
Common Error Patterns
Debugging Steps
Common Fixes
Environment Setup Dependencies
Rails Environment Required
Common Issues
Workarounds
Shakapacker Compatibility Issues
Version Compatibility Matrix
Common Upgrade Issues
Migration Steps
For Coding Agents
Automated Diagnostics
Quick Fixes Checklist
Error Pattern Recognition
Automated Solutions
Need More Help?
Troubleshooting When Using Shakapacker
Client rendering crashes when configuring optimization.runtimeChunk to multiple
Context
The failure
Configs
Webpack configuration
Rails view
The problem
Solution
Troubleshooting When Using Webpacker
Context
The failure
Configs
webpack.config.js
config/webpacker.yml
config/initializers/react_on_rails.rb
The problem
Solution
Upgrading
Upgrading React On Rails
Need Help Migrating?
General Upgrade Process
Upgrading to v16
Breaking Changes
Migration Steps
Common Upgrade Issues
Build Fails with Module Resolution Errors
Enhanced Features in v16
Upgrading to v13
Breaking Change
Upgrading to v12
Recent versions
Removed Configuration config.symlink_non_digested_assets_regex
i18n default format changed to JSON
Updated API for ReactOnRails.register()
Update required for registered functions taking exactly 2 params.
Broken, as this function takes two params and it returns a React Element from a JSX Literal
Upgrading rails/webpacker from v3 to v4
Custom Webpack build file
Upgrading to version 11
Upgrading to version 10
Upgrading to version 9
Why Webpacker?
Integrating Webpacker
From version 7 or lower
...while keeping your client directory
Client Webpack config
...while replacing your client directory
From version 8
Without integrating webpacker
15.0.0
16.0.0
Major Features
🚀 React Server Components Support
🚀 Major Performance Breakthrough: Early Hydration
Enhanced Script Loading Strategies
Breaking Changes
Component Hydration Changes
Script Loading Strategy Migration
ESM-only package
globalThis
Store Dependencies for Components
The Problem
The Solution
Migrating
Migrating From React Rails
Migrate From react-rails
Angular Js Integration Migration
Assets Handling
Styling and CSS Modules
ngReact Package
StoryBook
Overall Approach?
Convert Rails 5 Api Only App
Pro
React On Rails Pro
Pro: Docs
Pro: React Server Components
Pro: Fragment Caching
Pro: Integration with Node.js for Server Rendering
Major Performance Breakthroughs Upgrade Guide
🎯 What This Means for Your Applications