Installing and Testing React

Learn to install and test React in our Ruby app.

We need a dynamic form that changes what fields are shown based on what pay type the user has selected. While we could cobble something together with jQuery, it would be cleaner if we could use a more modern JavaScript library like React. This will also form a solid base from which we can easily add additional features later.

Using JavaScript libraries or frameworks can often be difficult, as the configuration burden they bear is far greater than what we’ve seen with Rails. To help us manage this complexity, Rails includes Webpacker, which provides configuration for Webpack. Webpack is a tool to manage the JavaScript files that we write. Note the similar names. Webpacker is a gem that’s part of Rails and sets up Webpack inside our Rails app.

Managing JavaScript is surprisingly complex. By using Webpack, we can easily put our JavaScript into several different files, bring in third-party libraries like React, and use more advanced features of JavaScript not supported by a browser like the ability to define classes. Webpack then compiles all of our JavaScript, along with the third-party libraries we are using, into a pack. Since this isn’t merely sprinkling small bits of JavaScript in our view, Rails refers to this as app-like JavaScript.

While we could use Webpack directly with Rails, configuring Webpack is extremely difficult. It’s highly customizable and not very opinionated, meaning developers must make many decisions just to get something working. Webpacker is essentially the decisions made by the Rails team and bundled up into a gem. Almost everything Webpacker does is to provide a working configuration for Webpack and React so that we can focus on writing JavaScript instead of configuring tools, but Webpack is the tool that manages our JavaScript day-to-day.

React is a JavaScript view library designed to quickly create dynamic user interfaces. We’ll use it to create a dynamic payment method details form, and Webpacker will ensure that the configuration and setup for all this is as simple as possible. That said, there’s a bit of setup we need to do.

First, we’ll use Webpacker to install React. After that, we’ll replace our existing payment-type drop-down with a React-rendered version, which will demonstrate how all the moving parts fit together. With that in place, we’ll enhance our React-powered payment type selector to show the dynamic form elements we want.

Installing React

Webpacker can install and configure some common JavaScript frameworks such as Angular, Vue, or React. We chose to React because it’s the simplest overall and is the best fit for solving our problem. To have Webpacker set it all up for us, run the task webpacker:install:react:

$ bin/rails webpacker:install:react

Get hands-on with 1200+ tech skills courses.