I'm struggling with integrating React into my Rails4 application(just upgraded from Rails3). I'm sort of at a standstill here because I'm getting no console errors and the React component is being "rendering" onto the page with nothing processed in the render call.
What I've done:
- Add
react-railsandwebpackerto my Gemfile - Followed Gracefully integrate Reactjs with Ruby on Rails in SaaS Applications
a.bundle install
b.rake webpacker:install
success Saved lockfile.
success Saved 1 new dependency.
info Direct dependencies
└─ [email protected]
info All dependencies
└─ [email protected]
Done in 21.05s.
Webpacker successfully installed
c. rake webpacker:install:react
success Saved 5 new dependencies.
info Direct dependencies
├─ @babel/[email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
└─ [email protected]
info All dependencies
├─ @babel/[email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
└─ [email protected]
Done in 11.59s.
Webpacker now supports react.js
d. rails generate react:install
exist app/javascript/components
create app/javascript/components/.keep
append app/javascript/packs/application.js
identical app/javascript/packs/server_rendering.js
- Add
<%= javascript_pack_tag 'application' %>to myapplication.html.erbfile rails g react:component HelloWorld greeting:string
a. Which creates the component atapp/assets/javascript/HelloWorld.jsrails g controller greetings hello
create app/controllers/greetings_controller.rb
route get 'greetings/hello'
invoke erb
create app/views/greetings
create app/views/greetings/hello.html.erb
invoke test_unit
create test/controllers/greetings_controller_test.rb
invoke helper
create app/helpers/greetings_helper.rb
invoke test_unit
invoke assets
invoke coffee
create app/assets/javascripts/greetings.coffee
invoke scss
create app/assets/stylesheets/greetings.scss
- Place the
react_componenthelper call inside ofhello.html.erb(for greetings)
<h1>Greetings#hello</h1>
<p>Find me in app/views/greetings/hello.html.erb</p>
<%= react_component("HelloWorld", { greeting: "Hello from react-rails." }) %>
- Visiting the route at
localhost:3000/greetings/hellogives me:
What am I missing here?
Extra information:
webpacker.yml
default: &default
source_path: app/javascript
source_entry_path: packs
public_root_path: public
public_output_path: packs
cache_path: tmp/cache/webpacker
check_yarn_integrity: false
webpack_compile_output: true
# Additional paths webpack should lookup modules
# ['app/assets', 'engine/foo/app/assets']
resolved_paths: []
# Reload manifest.json on all requests so we reload latest compiled packs
cache_manifest: false
# Extract and emit a css file
extract_css: false
static_assets_extensions:
- .jpg
- .jpeg
- .png
- .gif
- .tiff
- .ico
- .svg
- .eot
- .otf
- .ttf
- .woff
- .woff2
extensions:
- .jsx
- .mjs
- .js
- .sass
- .scss
- .css
- .module.sass
- .module.scss
- .module.css
- .png
- .svg
- .gif
- .jpeg
- .jpg
development:
<<: *default
compile: true
# Verifies that correct packages and versions are installed by inspecting package.json, yarn.lock, and node_modules
check_yarn_integrity: true
# Reference: https://webpack.js.org/configuration/dev-server/
dev_server:
https: false
host: localhost
port: 3035
public: localhost:3035
hmr: false
# Inline should be set to true if using HMR
inline: true
overlay: true
compress: true
disable_host_check: true
use_local_ip: false
quiet: false
pretty: false
headers:
'Access-Control-Allow-Origin': '*'
watch_options:
ignored: '**/node_modules/**'
test:
<<: *default
compile: true
# Compile test packs to a separate directory
public_output_path: packs-test
production:
<<: *default
# Production depends on precompilation of packs prior to booting for performance.
compile: false
# Extract and emit a css file
extract_css: true
# Cache manifest.json for performance
cache_manifest: true
rake webpacker:info
Ruby: ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]
Rails: 4.2.11.3
Webpacker: 4.3.0
Node: v14.21.3
Yarn: 1.22.19
app/assets/javascript/packs/application.js
var componentRequireContext = require.context("components", true);
var ReactRailsUJS = require("react_ujs");
ReactRailsUJS.useContext(componentRequireContext);
babel.config.js
module.exports = function(api) {
var validEnv = ['development', 'test', 'production']
var currentEnv = api.env()
var isDevelopmentEnv = api.env('development')
var isProductionEnv = api.env('production')
var isTestEnv = api.env('test')
if (!validEnv.includes(currentEnv)) {
throw new Error(
'Please specify a valid `NODE_ENV` or ' +
'`BABEL_ENV` environment variables. Valid values are "development", ' +
'"test", and "production". Instead, received: ' +
JSON.stringify(currentEnv) +
'.'
)
}
return {
presets: [
isTestEnv && [
'@babel/preset-env',
{
targets: {
node: 'current'
},
modules: 'commonjs'
},
'@babel/preset-react'
],
(isProductionEnv || isDevelopmentEnv) && [
'@babel/preset-env',
{
forceAllTransforms: true,
useBuiltIns: 'entry',
corejs: 3,
modules: false,
exclude: ['transform-typeof-symbol']
}
],
[
'@babel/preset-react',
{
development: isDevelopmentEnv || isTestEnv,
useBuiltIns: true
}
]
].filter(Boolean),
plugins: [
'babel-plugin-macros',
'@babel/plugin-syntax-dynamic-import',
isTestEnv && 'babel-plugin-dynamic-import-node',
'@babel/plugin-transform-destructuring',
[
'@babel/plugin-proposal-class-properties',
{
loose: true
}
],
[
'@babel/plugin-proposal-object-rest-spread',
{
useBuiltIns: true
}
],
[
'@babel/plugin-transform-runtime',
{
helpers: false,
regenerator: true,
corejs: false
}
],
[
'@babel/plugin-transform-regenerator',
{
async: false
}
],
isProductionEnv && [
'babel-plugin-transform-react-remove-prop-types',
{
removeImport: true
}
]
].filter(Boolean)
}
}
Gemfile
source 'https://rubygems.org'
gem 'rails', '4.2.11.3'
# A Ruby wrapper for Linux inotify, using FFI
gem 'rb-inotify', :require => false
# FSEvents API with Signals catching (without RubyCocoa)
gem 'rb-fsevent', '~> 0.9.1'
# A Ruby wrapper for Windows Kernel functions for monitoring the specified directory or subtree
gem 'rb-fchange', :require => false
# The Ruby interface to the PostgreSQL RDBMS
gem 'pg', '~> 0.17.1'
# Annotates Rails/ActiveRecord Models, routes, fixtures
gem 'annotate', '2.6.0'
# Flexible authentication solution for Rails with Warden
gem 'devise', '3.4.0'
# Authorization solution for Rails which is decoupled from user roles
gem 'cancan'
# Markdown to (X)HTML parser
gem 'redcarpet'
# An interface between Ruby and ImageMagick.
gem 'rmagick'
# Structured (X)HTML/XML templating engine.
gem 'haml'
# Extension of CSS, adding nested rules, variables, mixins, selector inheritance,
gem 'sass'
# Provides jQuery and the jQuery-ujs driver
gem 'jquery-rails'
# Process incoming emails with a simple routing DSL
gem 'mailman'
gem 'mailman-rails'
# Cron jobs in Ruby
gem 'whenever', :require => false
# ActiveRecord backend for Delayed::Job
gem 'delayed_job_active_record'
# Ruby debugging companion; pretty print Ruby objects to visualize structure
gem 'awesome_print'
# Implements a PDF parser conforming as much as possible to the PDF specification from Adobe
gem 'pdf-reader'
# Documentation generation tool
gem 'yard'
# A module for encoding and decoding (X)HTML entities.
gem 'htmlentities'
# Provides both resource oriented interfaces and API clients for AWS services.
gem "aws-sdk", "< 2.0"
gem 'aws-partitions', '~> 1.748.0'
# Web server
gem 'thin'
# ruby wrapper for posting to slack webhooks
gem 'slack-notifier', '1.5.1'
# Adds support for creating state machines for attributes on any Ruby class
gem "state_machines-activerecord"
# Simple (but safe) token authentication for Rails apps or API with Devise.
gem 'simple_token_authentication'
# Used to send messages via email/slack upon exceptions thrown
gem 'exception_notification', '4.1.1'
# Used for managing uploads within Ruby Models
gem "paperclip"
# SOAP client
# Latest Savon version to not depend on {Nokogiri: Ruby 2.5}
gem 'savon', '0.9.1'
# A generalized Rack framework for multiple-provider authentication.
gem 'omniauth'
# AREL integrated into Active Record
gem "squeel"
# Provides an easy way to wrap existing ruby scripts to be run as a daemon and to be controlled by simple start/stop/restart commands - used with delayed_jobs
gem "daemons"
# Meant to serve the use-case of connecting, querying and iterating over results to Microsoft SQL Server
gem "tiny_tds", '1.3.0'
# AWS S3 integration
gem "aws-sdk-s3"
# Supports mass assignment until Rails 5.0
gem 'protected_attributes'
# Re-enables deprecated finder methods
gem "activerecord-deprecated_finders"
# REST on Rails
gem 'activeresource'
# Re-enables respond_with/respond_to
gem 'responders', '~> 2.0'
# # Asset compilation strategy
gem 'webpacker', '~> 4.3.0'
# React in Rails
gem 'react-rails'
group :production, :staging do
# Call JavaScript code and manipulate JavaScript objects from Ruby. Call Ruby code and manipulate Ruby objects from JavaScript.
gem 'therubyracer', :platforms => :ruby
# Lets you run JavaScript code from Ruby.
gem 'execjs'
# Faster process spawning
gem 'posix-spawn'
end
group :test do
# TODO looking to replace with the default testing suite of rails 4.2
# Adds Minitest as the default testing library in Rails
gem 'minitest-rails', '~> 2.2', '>= 2.2.1'
# Used to ensure a clean state for testing in conjunction with minitest
gem 'database_cleaner-active_record'
# Rails performance testing helpers
gem 'rails-perftest'
# General Purpose cryptography
gem 'openssl', '2.0.2'
end
group :development do
# Code profiler for Ruby
gem 'ruby-prof', '0.18.0'
# Client Side profiling, DB profiling and Server profiling.
gem 'rack-mini-profiler', '2.0.2'
# Supporting gem for Rails Panel
gem 'meta_request'
# Used for advanced debugging in development environment
gem "binding_of_caller"
# Turns off Rails asset pipeline log.
gem 'quiet_assets'
# Help to kill N+1 queries and unused eager loading.
gem "bullet"
# IRB alternative with powerful introspection capabilities
gem 'pry'
# Turns Pry into a primitive debugger
gem 'pry-nav'
# Enables irb console to be used in the view, actively debugging the page on error.
gem 'web-console', '~> 2.0'
end
group :assets do
# Sass adapter for the Rails asset pipeline.
gem 'sass-rails', '~> 5.0'
# CoffeeScript adapter for the Rails asset pipeline.
gem 'coffee-rails', '~> 4.1.1'
# jQuery UI's JavaScript, CSS, and image files packaged for the asset pipeline
gem 'jquery-ui-rails'
# Recompiles changed assets for the asset pipeline
gem 'turbo-sprockets-rails4'
# Select2 with Rails asset pipeline
gem "select2-rails"
# Minifies JavaScript files by wrapping UglifyJS to be accessible in Ruby
gem 'uglifier', '>= 1.0.3'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
end
