How to use React.js with Ruby on Rails 5
Hrishi Mittal
Posted on July 24, 2017
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>
Install the gem:
bundle install
Run the react-rails installation script:
rails g react:install
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>
)
}
});
Finally, use the component in your view with the react_component helper method.
<%= react_component('HelloMessage', name: 'John') %>
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"
Install it by running bundle:
bundle
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"
Then run the gem's generator to create the package.json and Procfile.dev files:
rails generate react_on_rails:install
Then run bundle again for installing execjs and npm install for installing JS dependencies:
bundle && npm install
Then, start the Rails server with foreman:
foreman start -f Procfile.dev
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>
);
}
}
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'}) %>
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.
Posted on July 24, 2017
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 5, 2023