There is lot of buzz(12) around ReactJS and lot many tech companies started using it in productionThoughtworks has already adopted and is strongly recommending to use it in production.

I am in love with React because of these 7 strengths of it. As a Rails developer, If I have to choose one of the Javascript Framework in my project then I will go with React.

In this post, I am going to explain how to integrate a ReactJS in a Rails application.

Let’s start with creating a new Rails application
rails new my_react_app
Now, Edit your Gemfile, add ‘react-rails’ gem and bundle.
gem 'react-rails'
This gem gives a generator to install required scripts. So run following command to finish installation:
rails g react:install
ReactJS with Rails

It will insert three react specific files in your application.js manifest file.
//= require react
//= require react_ujs
//= require components

and also creates a ‘component’ directory inside app/javascript directory where you will place all your React components.

Now just to ensure installation was working, I am going to demonstrate a small working React component with Rails. The component would display list of users with name, email, phone number.

So lets create a User model,
rails g model User name:string phone:string email:string
rake db:create
rake db:migrate

Let’s add some data to display from the console.
User.create(name: 'Nishant', email: 'nishant@mail.com', phone: '123–456–7890')

User.create(name: ‘John’, email: ‘john@mail.com’, phone: ‘321–645–7840’)
Now, Create UsersController with index action to handle request from React component
rails g controller users index
Update your route file for user resources.
root 'users#index'
resources :users

Modify index action to return list of users
def index
@ users= User.all
end

Create index.html.erb file inside views/users and add following line:
<%= react_component 'Users', { data: @ users} %>
Note: This helper method is provided by react-rails gem.

Now start the server and hit http://localhost:300 0. Check generated HTML in view source or browser’s development tool. You would find something similar like shown below.

react rails gem

react_component helper of react_ujs will identify that we are trying to render a React component so it will be instantiated by it with the attributes we sent through react_component, in our case, the contents of @users

Now lets write a React component to render users.

Create a users.js file inside assets/javascripts/components and add following code inside it,
this.User = React.createClass({
render: function() {
return React.DOM.div({
className: ‘records’
}, React.DOM.h2({
className: ‘title’
}, ‘Records’));
}
});

For above code you can also use JSX syntax but I prefer using the React.DOM syntax over JSX because the code will arrange in a hierarchical structure by itself, similar to HAML. On the other hand, if you are trying to integrate React into an existing application built with erb, you have the option to reuse your existing erb code and convert it into JSX.

Refresh your browser screen, and you will see “User” title.

user react js

Perfect! We have rendered our first React Component.

Now, it’s time to display users’ details.

Besides the render method, React components rely on the use of properties to communicate with other components and states to detect whether a re-render is required or not.

We need to initialize our component’s state and properties with the desired values:
...
getInitialState: function() {
return {
users: this.props.data
};
},
getDefaultProps: function() {
return {
users: []
};
},
...

The method getDefaultProps will initialize our component’s properties in case we forget to send any data when instantiating it, and the getInitialStatemethod will generate the initial state of our component.

Now we need to actually display the records provided by our Rails view. We have to create a new User component to display each individual record,

Create a new file user.js under the javascripts/components/ directory and insert the following contents:
this.User = React.createClass({
render: function() {
return React.DOM.tr(null,
React.DOM.td(null, this.props.record.name),
React.DOM.td(null, this.props.record.email),
React.DOM.td(null, this.props.record.phone)
);
}
});

Now, Add below changes in components/users.js

render: function() {
var user;
return React.DOM.div({
className: ‘users’
}, React.DOM.h2({
className: ‘title’
}, ‘Users’), React.DOM.table({
className: ‘table’
}, React.DOM.thead(null,
React.DOM.tr(null, React.DOM.th(null, ‘Name’),
React.DOM.th(null, ‘Email’),
React.DOM.th(null, ‘Phone’))),
React.DOM.tbody(null, (function() {
var i, len, ref, results;
ref = this.state.users;
results = [];
for (i = 0, len = ref.length; i < len; i++) {
record = ref[i];
results.push(React.createElement(User, {
key: record.id,
record: record
}));
}
return results;
}).call(this))));
}


Here I have added a table with table headers and for each individual user a User ‘component’ is getting created which is nested with parent(table)

We are also adding key property and passing id to handle this dynamic children.

Now refresh your browser again and see the result.

users - local host

Voila!! We rendered data using React component backed by beloved Rails.

I know it looks brittle but in my next post we will integrate it with material-ui. So keep in touch!

Complete Source code is available a github repository.


Click here for more details…

Consulting is free – let us help you grow!