Serve react component with Rails

Satendra Rai
ITNEXT
Published in
2 min readFeb 21, 2018

--

webgrinder.pl

Using React as frontend with Rails backend is an amazing combination. I am using react-rails gem for that, which is a flexible tool to use React with Rails.

Click here to share this article on LinkedIn »

Use with Sprockets Asset Pipeline

Add react-rails to the Gemfile.

gem 'react-rails'

Followed with below commands

$ bundle install
$ rails g react:install

The react:install generator will automatically include the react JavaScript library in your asset pipeline

create app/assets/javascripts/components 
insert app/assets/javascripts/application.js
create app/assets/javascripts/components.js
create app/assets/javascripts/server_rendering.js
create config/initializers/react_server_rendering.rb

Setup completed!

The first component

The first thing we need to do is to set-up a jsx file in our components folder.

// app/assets/javascripts/components/first.es6.jsx class FirstComponent extends React.Component{   constructor(props, context) {
super(props, context);
this.state = {
name: props.name,
};
}
componentDidMount(){} render() {
return (
<div>
<h1>Hello: {this.state.name}</h1>
</div>
)
}
}

Read: The react component lifecycle

Server Side Rendering

To make Rails render React components, there are 2 ways.

Use react_component view helper

Use react_component helper method in your views i.e index.html.erb

<%= react_component('FirstComponent', {name: 'John'}, {prerender: true}) %>

The react_component is part of react-rails. In this case, it’s used to put the component named FirstComponent from the components folder in the assets directory into the view.

Use controller action

The react-rails gem allows us to create a controller action that will render the react component. This eliminates the need for an html.erb template.

# app/controllers/some_controller.rb
class SomeController < ApplicationController
def index
render component: 'FirstComponent', props: { name: 'Jhon' }
end
end

Great! We just render our first component.

Conclusion

Using react-rails makes it is possible to create, some part of a page using embedded ruby HTML and some part using react component. WOW..

(Help others to find my article on Medium by giving it 👏🏽 below.)

--

--