Learn Ruby on Rails Book

Bring React.js to Rails

Adding React-Rails gem

We will be using React.js to build frontend of our application. We will use react-rails gem to bring React to our Ruby on Rails application and hook it into the webpacker compilation system.

Add following line to the end of the Gemfile:

1gem 'react-rails'

Execute bundle install after adding a new gem to Gemfile:

1bundle install

Execute the following commands in the terminal and we will see components folder being created in the app/javascript directory.

1bundle exec rails webpacker:install # enter n when prompted

In the above command, enter n (no) when prompted and continue with the rest of its execution. This should be done so as to not override the existing config/webpacker.yml file that was generated when we setup the project.

1bundle exec rails webpacker:install:react
2bundle exec rails generate react:install

We have successfully added React.js support to our application.

Before committing let's remove the unwanted files which were generated after running above commands:

1rm -rf app/javascript/packs/server_rendering.js app/javascript/packs/hello_react.jsx

Also remove the redeclaration of componentRequireContext with components as argument from application.js, if exists.

Now let's commit the changes:

Note: npm install command would add package-lock.json which isn't required as we are using Yarn. Thus avoid using npm install. If executed then please don't commit package-lock.json file. Add package-lock.json to the .gitignore file. Use yarn add for installing new packages.

1git add -A
2git commit -m "Added React.js to the project"