How to handle data binding in Rails when using React.js for an interface?

I am interested in creating an isomorphic application that will use React.js for the front end, and Rails for everything else.

I'm sure I will use a decent amount of AJAX, but for the primary form and page changes, I want to go through a Rails router. I do not want to use Javascript to control which views I display on the client.

My only question is: what is the best way to configure my React inputs so that they communicate with my models in Rails?

In regular erb, you must create a form object for this model, and then use the input methods for this object to create HTML inputs that are already configured so that the data binding is pretty automatic when sending.

The only way I can do this with something like React is to manually set the attribute nameon my inputs so that they are properly bound. I think it's not scary, I'm just wondering if anyone has a better solution.

+4
source share
1 answer

Create a client side (React model) to “reflect” the rails response. For example, on the side of the rails:

class Message < ActiveRecord::Base
  belongs_to :thread

  validate :text, presence: true
end

The JSON response sent by the index / new server endpoint should determine the structure of the data model on the client side. For example, the index endpoint may return:

{
  "messages": [
    {
      "id": "1",
      "text": "Hello Stack",
      "threadId": "5"
    } 
  ]
}

Client Side Model:

var Message = function Model(){
  this.id = null;
  this.text = null;
  this.threadId = null;
};

Message.fromJSON = function(messageJSON) {
  var message = new Message();
  message.id = messageJSON.id;
  // ...
  return message;
};

module.exports = Message;

Then when creating / editing just call JSON.stringfy (msg).

0
source

All Articles