Configuring ReactJS in Rails with Webpacker
Source: Dev.to
Prerequisites
- Ruby 2.5.1 or higher
- Rails 5.2.1 or higher
- Webpacker 3.5.5 or higher
Create a new Rails app with Webpacker
rails new rails-with-reactjs --skip-test --webpack
The command creates the application and sets up Webpacker, skipping the test structure.
Install React via Webpacker
bundle exec rails webpacker:install:react
This command:
- Adds a Babel configuration at the project root.
- Creates an example pack at
app/javascript/packs/hello_react.jsx. - Updates Webpacker to resolve
.jsxfiles. - Installs all required React dependencies.
The generated
hello_react.jsxinjects a component directly into the “.
It’s usually better to organize components in a dedicated folder and mount them withreact-rails.
Add react-rails gem
Add the gem to your Gemfile:
gem 'react-rails'
Then run:
bundle install
Install the JavaScript driver used by react-rails:
yarn add react_ujs
react_ujs scans the page and mounts components using data-react-class and data-react-props.
Organize React components
Create a folder for your components and add a simple component:
mkdir -p app/javascript/components
touch app/javascript/components/hello_world.jsx
app/javascript/components/hello_world.jsx
import React, { Component } from 'react';
export default class HelloWorld extends Component {
render() {
return
## Hello World
;
}
}
Register components with react-rails
Edit app/javascript/packs/application.js and add the following at the end:
// app/javascript/packs/application.js
const componentRequireContext = require.context('components', true);
const ReactRailsUJS = require('react_ujs');
ReactRailsUJS.useContext(componentRequireContext);
Update the layout
Replace the default asset‑pipeline JavaScript tag with the Webpacker pack tag in app/views/layouts/application.html.erb:
Create a controller and route
Generate a simple controller for a static page:
rails g controller pages index --no-helper --no-assets --no-controller-specs --no-view-specs
Update config/routes.rb:
# config/routes.rb
root 'pages#index'
Render the React component in a view
In app/views/pages/index.html.erb:
Run the application
Start the Rails server:
rails s
In a separate terminal, start the Webpack dev server for live compilation:
bin/webpack-dev-server
Visit http://localhost:3000 – you should see Hello World rendered by React.
References
- GitHub example repository
- Official Rails/Webpacker documentation
react-railsgem documentation