Connecting a Rails Backend to a React Frontend

This article is a big picture look at how you can go about connecting a backend framework like Ruby on Rails to a frontend framework like React or Angular. I created this diagram to help make sense of how the process works.

Rails React Model View Controller Architecture.png.png

One way to get the frontend and backend communicating is through "serialization". Serialization is the process of turning data and objects written in one language into a format that can be used more robustly later. JSON or "JavaScript object notation" is a commonly used format for serialized information for working on the web. When working with Ruby on Rails, you store information about your models in the server and you might want to send that information to a React front end to dynamically generate some views for your website.

To get information from the database you can query it in the controller and output that JSON using a serializer gem like 'fast_jsonapi'. From the react side you can use fetch or something like axios to access the JSON from its routed path. If you are using Webpacker, then you can throw a javascript_pack_tag into your views/layouts/application.html.erb file to link to your javascript/packs/index.js file. This index file is where you will ReactDOM.render all of the components you code for your front end.

This Harry Lavine article does a great job of walking you through the specifics.

I also recommend this youtube series by zayne for getting some exposure to one implementation of a Ruby on Rails backend working with a React front end.

No Comments Yet