1

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.

João Paulo Motta
  • 3,765
  • 1
  • 19
  • 18

1 Answers1

0

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.

João Paulo Motta
  • 3,765
  • 1
  • 19
  • 18
  • 2
    `react_component` is a ruby method and understands correctly (and does json serialization) of ruby hashes. If you use `to_json`, instead, you pass a string to it, so `phase` would be a string, but that's not what you want. You want an object with all the properties you set. `as_json` creates a hash (which is basically a JSON object) in the same way `to_json` does but skips the "convert to string" part (`to_json` calls `as_json` and then converts to string under the hood) – Francesco Belladonna Aug 06 '15 at 03:17