Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show Associated Model Data with React Rails

I'm using the react-rails gem and have two models: Message and User. User has_many :messages.

In my message.js.jsx, I'd like to show the User of that message. In regular erb, it'd just be <%= message.user.name %>. How would I do this in the message.js.jsx component?

like image 966
leejay100 Avatar asked May 18 '26 10:05

leejay100


1 Answers

You could rename your component to message.js.jsx.erb and use ERB in it, but it will only be compiled once when Rails starts up.

A more React-ish way to handle is to AJAX load the user data in componentDidMount (or a Store, if using Flux).

message.js.jsx

getInitialState: function() {
  return { user: { name: '' } };
},

componentDidMount: function() {
  $.getJSON('/users/'+ this.props.id +'.json', function(userData) {
    if (this.isMounted()) {
      this.setState({ user: userData })
    }
  });
},

You can create a Rails endpoint to return userData as JSON something like this:

users_controller.rb

def show
  @user = User.find(params[:id])
  respond_to do |format|
    format.html # default html response
    format.json { render json: @user.to_json(only: [:id, :name]) }
  end
end

See Facebook's page on this for more details

like image 167
Unixmonkey Avatar answered May 21 '26 00:05

Unixmonkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!