Search code examples
ruby-on-railsreactjsreact-rails

react-rails gem not working with to_json


Whenever I try to pass other options to to_json on a react_component helper it is parsed just as plain string to the react prop.

<%= react_component "SelectableActivityLevel", 
  phase: UserService.active_phase(@user).to_json(methods: "pictures_url"),
  activity_levels: @activity_levels
%>

Results in

this.prop.activity_levels //Object (correct)
this.prop.phase //String (incorrect)

The documentation of the gem says:

props is either an object that responds to #to_json or an already-stringified JSON object (eg, made with Jbuilder, see note below).

This did not help a lot.

The Jbuilder example did't help also because I'm using to_json.

Thanks for you help.


Solution

  • I solved the problem using as_json instead

    <%= react_component "SelectableActivityLevel", 
      phase: UserService.active_phase(@user).as_json(methods: :pictures_url),
      activity_levels: @activity_levels
    %>
    

    Why?

    to_json was returning the string escaped. ex:

    => "{\"name\":\"bla bla\"}"
    

    And react-rails just puts the prop as string when it's a string. (line 3)

        html_options[:data].tap do |data|
          data[:react_class] = name
          data[:react_props] = (props.is_a?(String) ? props : props.to_json)
        end
    

    Don't know about performance issues for big collections, but I'm basically just serializing a simple object with a few fields, so I'm not worrying about it at all.