Having just migrated from ReactOnRails to Webpacker for handling the frontend code in my Rails app, I thought I’d share the steps I took. I switched because I was tired of having react on rails in both the Gemfile and client code, maintaining the same version in both and because Webpacker was supported by Rails in 5.1.
Migration steps
- Install Webpacker gem and run
rails webpacker:installandrails webpacker:install:react. - Run
webpackto verify it works - Merge packages and configurations from
client/package.jsontopackage.jsonandyarn install. - Move client into
app/javascriptsviacp -R client/app app/javascript. - Create corresponding entry files in
app/javascript/packs. - Rendering React components is now a little bit trickier without the helpers from ReactOnRails, but below is how I did it.
# in your template do something like this
<%= react_component('cloud', { files: some_files }) %>
# application_helper.rb
def react_component(pack, props)
content = javascript_pack_tag(pack.downcase)
content << content_tag(:div, nil, { id: 'container', data: props })
content.html_safe
end
// app/javascript/packs/cloud.js
import Component from '../cloud/cloud';
import ComponentRenderer from '../component-renderer';
ComponentRenderer(Component);
// component-renderer.js
import React from 'react';
import { render } from 'react-dom';
export default function ComponentRenderer(Component) {
document.addEventListener('DOMContentLoaded', () => {
const container = $('#container');
const myProps = container.data();
render(<Component {...myProps} />, container.get(0));
});
}
Testing
Run RAILS_ENV=test webpack to build assets before running specs that need them, I used this
neat solution.
Conclusion
Overall the switch took a few days, but I think it’s worth it as I now have a
neat setup with webpack-dev-server and stylesheets in webpack, something I
didn’t get when first setting up ReactOnRails about a year ago. But the biggest
win here is moving away from the magic of ReactOnRails to something where I’ve
gained a much better understanding of all the moving parts, and I’m not better
positioned to deal with any issues going forward. That being said, I’d like to
thank the creators and maintainers of ReactOnRails for making it easy to get
started using React with Rails.
If you discover any quirks please share them in the comments below.