Jason Charnes

Installing React in Ruby on Rails with Webpacker

December 23, 2019 ∙ Jason Charnes

So, you want to use React in a Ruby on Rails application. I’m glad you’re here! I think React is a great tool to use in your Ruby on Rails applications.

I’ll help you get started. We’ll look at bootstrapping any Ruby on Rails application (that can use Webpacker) with React.

Luckily, for us, Ruby on Rails makes it pretty easy to get started.

Installing Webpacker

If you’re using Rails 6, no further action is required to install Webpacker. 🎉 Good job, I’m proud of you.

If you’re starting a fresh Rails 6 application, jump to the bonus section.

If you’re using Rails 5, we’ll follow the Webpacker instructions.

A fresh Rails 5 application

If you’re starting fresh, you should consider using Rails 6. Out of the box, you’ll get Webpacker. But, If you need a new Rails 5 application, you can provide the --webpack option when creating your app:

rails new react-app --webpack
An existing Rails 5 application

If you’re adding Webpacker to a pre-existing Rails 5 application, add the following to your Gemfile:

# In Gemfile
gem "webpacker", "~> 4.x"

Once you’ve run bundle install, you can install Webpacker using the following command in your terminal:

bundle exec rails webpacker:install

Installing React in Ruby on Rails

Once again, thanks to Webpacker, this is a simple step. Rails gives us a command to run that allows us to bootstrap our application with React.

Run the following command in your terminal:

bundle exec rails webpacker:install:react

Running this command adds React to your application, run yarn install, and create a React component you can immediately use in your application.

Bonus

If you’re starting a brand new Rails 6 application, you can bootstrap your application with React when using rails new.

rails new react-app --webpack=react

That’s all, folks

See, that wasn’t so bad. A sincere thank you to the team working on Webpacker. We couldn’t ask for a better install process for React in Ruby on Rails.

If you want to dissect the component Rails just created in app/javascript, you can join me here.