Did you know there’s a gem for that?

Andrew Alteri
2 min readJun 19, 2021
Romancing the Stone

Ruby on Rails is an incredible framework for rapid web development, but it does not mean it is the perfect tool for every scenario. While working on a Rails project, I noticed that my app was lacking a dynamic oomph that only a frontend framework can provide. I did not want to start over with a JavaScript frontend because I only wanted to add a few JS components, and I still wanted to use Ruby as my primarily programming language. So how do I incorporate a frontend framework that easily passes Ruby data to components? BAM! ‘react-rails’ is the gem for me! This gem will allow you to develop in a Rails environment while seamlessly integrating React components. Let me show you the installation steps.

(These are the instructions for Rails 6, but here is the full documentation if you are running an older Rails version.)

After creating a new Rails app, add two gems to your Gemfile, gem ‘webpacker’ and gem ‘react-rails’. Then bundle install your gems. Then install everything with $ rails webpacker:install and $ rails webpacker:install:react. After everything is successfully installed, run $ rails g react:install in the terminal. This will set up a directory for your React components and set up server-side rendering.

Now that ‘react-rails’ is ready to go, let us explore a simple example.

I type $ rails g react:component Raiders into the terminal. That command generates this code:

react-rails template code

Now I will add something awesome like “<h1> Congrats Raiders of the Lost Ark on your 40th Anniversary! </h1>” between the React fragments. After that all I have to do is call the component in a view page with “<%= react_component(‘Raiders’) %>”, and when I start up my rails server the header will be displayed in the browser.

As you can see, it’s easy to add React components with the react-rails gem. Go forth and add some React to your fantastic Ruby on Rails app!

--

--