Basic Tutorial for React and Rails

5 Min. Read
Sep 22, 2019

Setting up the environment

Trying out React and Rails is super easy, so long as you have the basic prerequisites. This includes the basics for Rails 5.x and node version 6+. I recommend rvm and nvm to install Ruby and Node, and brew to install yarn. Rails can be installed as an ordinary gem.

1
2
3
4
5
6
7
8
9
10
11
nvm install node                # download and install latest stable Node
nvm alias default node          # make it default version
nvm list                        # check

brew install yarn               # you can use other installer if desired
11\.\d+\.\d+
rvm install 2.5.0               # download and install latest stable Ruby (update to exact version)
rvm use 2.5.0 --default         # use it and make it default
rvm list                        # check

gem install rails               # download and install latest stable Rails

Creating a New Rails Application

In this step you will create a fresh Rails application with webpacker react support as following.

1
$ rails new test-react-on-rails -d=postgresql --webpack=react

The preceding command creates a new Rails application in a directory named test-react-on-rails, installs the required Ruby and JavaScript dependencies, and configures Webpack. Let’s walk through the flags that are associated with this new generator command:

  • The -d flag specifies the preferred database engine, which in this case is PostgreSQL.
  • The –webpack instructs Rails to preconfigure for JavaScript with the webpack bundler, in this case specifically for a React application.

Once the command is done running, move into the test-react-on-rails directory, which is the root directory of your app and also run bundle:

1
2
$ cd test-react-on-rails
$ bundle

This root directory has a number of auto-generated files and folders that make up the structure of a Rails application, including a package.json file containing the dependencies for a React application.

Now open the project in any IDE(Integrated Development Environment) you are comfortable with and start coding. Visit http://localhost:3000 to see your app running.

Installing Frontend Dependencies

In this step, you will install the JavaScript dependencies needed on the frontend of our application. They include:

  • React Router, for handling navigation in a React application.
  • Bootstrap, for styling your front-end components.
  • jQuery and Popper, for working with Bootstrap.

Run the following command in your Terminal window to install these packages with the Yarn package manager:

1
$ yarn add react-router-dom bootstrap jquery popper.js

This command uses Yarn to install the specified packages and adds them to the package.json file. To verify this, take a look at the package.json file located in the root directory of the project:

1
$ nano package.json

You’ll see the installed packages listed under the dependencies key inside ~/test-react-on-rails/package.json folder:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
  "name": "rails_react_recipe",
  "private": true,
  "dependencies": {
    "@babel/preset-react": "^7.0.0",
    "@rails/webpacker": "^4.0.7",
    "babel-plugin-transform-react-remove-prop-types": "^0.4.24",
    "bootstrap": "^4.3.1",
    "jquery": "^3.4.1",
    "popper.js": "^1.15.0",
    "prop-types": "^15.7.2",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-router-dom": "^5.0.1"
  },
  "devDependencies": {
    "webpack-dev-server": "^3.7.2"
  }
}

You have installed a few front-end dependencies for your application. Next, you’ll set up a homepage for your application.

Setting Up the Homepage

With all the required dependencies installed, in this step you will create a homepage for the application. The homepage will serve as the landing page when users first visit the application.

Rails follows the Model-View-Controller architectural pattern for applications. In the MVC pattern, a controller’s purpose is to receive specific requests and pass them along to the appropriate model or view. Right now the application displays the Rails welcome page when the root URL is loaded in the browser. To change this, you will create a controller and view for the homepage and match it to a route.

Rails provides a controller generator for creating a controller. The controller generator receives a controller name, along with a matching action.

Run the following command in your Terminal window to create a Homepage controller with an index action.

1
$ rails g controller Homepage index

Inside the config/routes.rb, replace get 'homepage/index' with root 'homepage#index'.

This modification instructs Rails to map requests to the root of the application to the index action of the Homepage controller, which in turn renders whatever is in the index.html.erb file located at app/views/homepage/index.html.erb on to the browser. Opening the application in the browser, you will see a new landing page for your application.

Configuring React as Your Rails Frontend

In this step, you will configure Rails to use React on the frontend of the application, instead of its template engine. This will allow you to take advantage of React rendering to create a more visually appealing homepage.

Rails, with the help of the Webpacker gem, bundles all your JavaScript code into packs. These can be found in the packs directory at app/javascript/packs. You can link these packs in Rails views using the javascript_pack_tag helper, and you can link stylesheets imported into the packs using the stylesheet_pack_tag helper. To create an entry point to your React environment, you will add one of these packs to your application layout.

Open application.html.erb, the application layout file and add the following highlighted lines of code in erb form at the end of the head tag in the application layout file:

1
 javascript_pack_tag 'hello_react'

Adding the JavaScript pack to your application’s header makes all your JavaScript code available and executes the code in your hello_react.jsx file on the page whenever you run the app.

Now that your entry file is loaded onto the page, create a React component for your homepage. Start by creating a components directory in the app/javascript directory:

1
$ mkdir ~/test-react-on-rails/app/javascript/components

The components directory will house the component for the homepage, along with other React components in the application.

In your editor, lets say create a Home.jsx file in the components directory which will be your landing react components for your front end application. Then in your app/packs/hello_react_jsx just render the home component as following:

1
2
3
4
5
6
7
8
9
10
import React from 'react'
import ReactDOM from 'react-dom'
import Home from '../components/home'

document.addEventListener('DOMContentLoaded', () => {
  ReactDOM.render(
    <Home />,
    document.body.appendChild(document.createElement('div')),
  )
})

Now you are good to go with your upcoming react and ruby application using this basic tutorial.