Estimate a project
Estimate Project

How to use React.js and RoR in a single application?

how to use React.jsToday, I’d like to talk about using React.js and RoR in a single application, where both draw the frontend. I faced such a necessity working on a recent project. I had a form with many features attached and it looked like this but multiplied within 7 days.

Originally, this was managed by jQuery. Any update of any field created a request to the server with the information about all fields. So, the things could run like this if only clients didn’t want to add a possibility to change or delete entities. But developing further with jQuery was kind of hard due to how many things I had to handle. I tried a few js-frameworks and decided to run React. First, I was a bit confused as I didn’t know how to start: either combine webpack with the asset-pipeline, or pack it manually on the server before deployment.

As usual, I started googling for any existing solution, and found two almost equal gems with the only distinction. One of them was unable to work with npm and was limited having only standard tools. So I preferred another React on rails gem. The installation was quite simple – the Gemfile and a configurator. After that let’s move on writing a React.js code. All files are stored in the /client folder, as well as the webpack configurator.

I want to draw your attention to the /config/app/app.js file. In my case, it looks like this:

This is a gem’s  way to wrap data and pass it to Rails to inform Rails about UI components. After the components are ‘registered’, we can use them in our Rails’ views, like this:

I want to highlight the flag prerender: true. Setting it to true make the component render on the server. Why did I use it? The answer is simple. My component was created in modal, requested through remote: true. For sure, you can render on the client as well, it is up to you.

The main action you need to take after such call from the server is to init react app, because when the page was loading, there were no react code at all.

This code initializes the React.js components and does all magic about rendering and other logic for the component. Now, you have only to write your components and use them.

As you see, it is quite easy, but at the same time, with the hybrid approach you can avoid writing  many jQuery codes and get more control over your app.This code initializes the React.js components and does all magic about rendering and other logic for the component. Now, you have only to write your components and use them.

Last but not the least, you can send data from the database directly to the react-application, which reduces server load, inessential requests and coding on both – server and client. Next actions depend on the project’s needs and targets. You can move all dynamic front-end to react with minimum effort.

 

Good luck!

RB_4

Tags: , ,