DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Hrishi Mittal for Learnetto

Posted on • Updated on • Originally published at learnetto.com

How to use React.js with Ruby on Rails 5

React with Ruby on Rails

Originally published at Learnetto.com.

IMPORTANT UPDATE (6 July 2017):Γ‚ With the release of Rails 5.1, Rails now has native support for using React via the webpacker gem. Check out the free lesson on how to do this in theΓ‚ Free React on Rails courseΓ‚ or seeΓ‚ this blog post.

There are a few different ways to useΓ‚ ReactΓ‚ inside Ruby on Rails apps. In this post, I'll cover 3 of the most popular ways.

*1.Γ‚ *react-rails gem (https://github.com/reactjs/react-rails)

The react-rails gem is the simplest and quickest way to start using React inside your Rails app.

It uses the default Rails asset management and automatically transforms JSX into the asset pipeline using the Ruby Babel transpiler.

Assuming you already have a recent version of Ruby and the Rails gem installed, here's how you get started with react-rails.

Add the gem to your Gemfile:

gem 'react-rails'</pre>
Enter fullscreen mode Exit fullscreen mode

Install the gem:

bundle install
Enter fullscreen mode Exit fullscreen mode

Run the react-rails installation script:

rails g react:install
Enter fullscreen mode Exit fullscreen mode

This will create a components directory, manifest file and add them to the application.js file.

Then create your React component file with a .jsx extension and save it underΓ‚ app/assets/javascripts/components.

var HelloMessage = React.createClass({
  render: function() {
    return (
      <h1>Hello {this.props.name}!</h1>
    )
  }
});
Enter fullscreen mode Exit fullscreen mode

Finally, use the component in your view with theΓ‚ react_componentΓ‚ helper method.

<%= react_component('HelloMessage', name: 'John') %>
Enter fullscreen mode Exit fullscreen mode

The method takes the name of the component as the first argument and any props as the second argument. It adds a div with the relevant class and props, which is then used by the react_ujs driver to mount and render the component.

That's all you need to get started!Γ‚

There's a whole lot more react-rails offers, including choosing react builds for your environment, server-side rendering, writing components in ES6 and component generators, which are covered in ourΓ‚ React on Rails course.

This gem allows you to start with React gradually and test the waters by converting individual views into React components. Once you're happy and confident with it, you can convert more and/or move to a more powerful setup.

*2.Γ‚ *react_on_rails gem (https://github.com/shakacode/react_on_rails)

This is another very popular gem for integrating React in Rails. The key difference with react-rails is that it uses EcmaScript 6 (ES6) by default and state-of-the-art JavaScript tooling, including Webpack, instead of relying completely on the Rails asset pipepline. It alsoΓ‚ doesn't depend on jQuery.

Instead of using the Rails asset pipeline for ES6 compilation, react_on_rails only uses it for including the JS that Webpack compiles.

You can use npm to install JavaScript libraries, instead of having to use gems or manually downloading and including them.

It gives you a lot more power at the cost of installing and managing a few extra things.

To get started, you need to install node so that you can use npm to install JavaScript dependencies. You can download node directly fromΓ‚ their websiteΓ‚ or install it usingΓ‚ nvm.

Once node is installed, we can start by adding the gem to the Gemfile of our Rails app:

gem "react_on_rails", "~> 6"
Enter fullscreen mode Exit fullscreen mode

Install it by running bundle:

bundle
Enter fullscreen mode Exit fullscreen mode

Now, we need to commit this to git, otherwise the gem's installation script won't work.

git init
git add -A
git commit -m "Initial commit"
Enter fullscreen mode Exit fullscreen mode

Then run the gem's generator to create the package.json and Procfile.dev files:

rails generate react_on_rails:install
Enter fullscreen mode Exit fullscreen mode

Then run bundle again for installing execjs and npm install for installing JS dependencies:

bundle && npm install
Enter fullscreen mode Exit fullscreen mode

Then, start the Rails server with foreman:

foreman start -f Procfile.dev
Enter fullscreen mode Exit fullscreen mode

We're using foreman to run Webpack, in addition to the Rails server.

Now that everything is set up, we can create and use React components.Γ‚

The gem's generator also creates a client directory, which is where all client-side code needs to go.Γ‚

A Hello World example is included under the client directory. Below is a simplified extract of the code for a component displaying a Hello message with a name passed as a prop.

import React from 'react';

export default class HelloWorld extends React.Component {
  constructor(props, _railsContext) {
    super(props);
  }

  render() {
    return (
      <h1>Hello, {this.props.name}!</h1>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

We can use the react_component helper method to render the component in a view in the same way we did with the react-rails gem.

<%= react_component("HelloWorldApp", props: {name: 'John'}) %>
Enter fullscreen mode Exit fullscreen mode

If you're already familiar with Webpack and modern JavaScript concepts and tooling, then go right ahead and start with react_on_rails. Otherwise, it might be better to get a feel for the core concepts of React with react-rails first and then move on to react_on_rails.

Have a look at theΓ‚ React on Rails doctrineΓ‚ to get some insight into the design decisions behind react_on_rails.

**3. Rails API with a separate frontend React app (Nodejs + Express)

**A third option for using React with Rails is to separate the backend and frontend into two different apps.Γ‚

The backend can either be a standard Rails app exposing some API endpoints with JSON output or it can be a Rails API-only app. The frontend is an Express app running on Nodejs, which uses React and talks to the Rails API.

Obviously, building, running and maintaining two separate apps is much more work. But there are some benefits.

Making an API may be a good idea anyway to enable you to build other clients like mobile apps (although note that you can use a Rails API with the gems too).

A Node app is the natural environment for a JavaScript library like React, so you may find you're more productive and always have access to the latest JS tooling by default. Server-side rendering of components is also faster.

If you work in a medium-large company with dedicated teams for backend and frontend development, then separating the two code bases makes sense.

You do have to deal with the complexities of running two apps. You either have to implement Cross Origin Resource Sharing (CORS) or proxy requests through a server like nginx.

This articleΓ‚ by Alex Fedoseev goes into some detail on what such a setup would look like. It's an excellent read to get an insight into what's involved and whether it's a suitable approach for you.

So that's 4 of the most popular methods of using React with Rails. Research and experiment with the ones you think make most sense for your situation and please leave a comment to share your experiences!

If you found this article useful, check outΓ‚ The Complete React on Rails coursefor detailed hands-on video lessons on using React with Rails.

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.