Module: ReactOnRailsHelper

Defined in:
app/helpers/react_on_rails_helper.rb

Instance Method Summary collapse

Instance Method Details

#react_component(component_name, props = {}, options = {}) ⇒ Object

react_component_name: can be a React component, created using a ES6 class, or

React.createClass, or a
  `generator function` that returns a React component
    using ES6
       let MyReactComponentApp = (props) => <MyReactComponent {...props}/>;
    or using ES5
       var MyReactComponentApp = function(props) { return <YourReactComponent {...props}/>; }
 Exposing the react_component_name is necessary to both a plain ReactComponent as well as
   a generator:
 See README.md for how to "register" your react components.
 See spec/dummy/client/app/startup/serverRegistration.jsx and
   spec/dummy/client/app/startup/ClientRegistration.jsx for examples of this

props: Ruby Hash or JSON string which contains the properties to pass to the react object

options:
  prerender: <true/false> set to false when debugging!
  trace: <true/false> set to true to print additional debugging information in the browser
         default is true for development, off otherwise
  replay_console: <true/false> Default is true. False will disable echoing server rendering
                  logs to browser. While this can make troubleshooting server rendering difficult,
                  so long as you have the default configuration of logging_on_server set to
                  true, you'll still see the errors on the server.
  raise_on_prerender_error: <true/false> Default to false. True will raise exception on server
     if the JS code throws
Any other options are passed to the content tag, including the id.


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'app/helpers/react_on_rails_helper.rb', line 33

def react_component(component_name, props = {}, options = {})
  # Create the JavaScript and HTML to allow either client or server rendering of the
  # react_component.
  #
  # Create the JavaScript setup of the global to initialize the client rendering
  # (re-hydrate the data). This enables react rendered on the client to see that the
  # server has already rendered the HTML.
  # We use this react_component_index in case we have the same component multiple times on the page.
  react_component_index = next_react_component_index
  react_component_name = component_name.camelize # Not sure if we should be doing this (JG)
  if options[:id].nil?
    dom_id = "#{component_name}-react-component-#{react_component_index}"
  else
    dom_id = options[:id]
  end

  # Setup the page_loaded_js, which is the same regardless of prerendering or not!
  # The reason is that React is smart about not doing extra work if the server rendering did its job.
  turbolinks_loaded = Object.const_defined?(:Turbolinks)

  data = { component_name: react_component_name,
           props: props,
           trace: trace(options),
           expect_turbolinks: turbolinks_loaded,
           dom_id: dom_id
  }

  component_specification_tag =
    (:div,
                "",
                class: "js-react-on-rails-component",
                style: "display:none",
                data: data)

  # Create the HTML rendering part
  result = server_rendered_react_component_html(options, props, react_component_name, dom_id)

  server_rendered_html = result["html"]
  console_script = result["consoleReplayScript"]

   = options.except(:generator_function, :prerender, :trace,
                                       :replay_console, :id, :react_component_name,
                                       :server_side, :raise_on_prerender_error)
  [:id] = dom_id

  rendered_output = (:div,
                                server_rendered_html.html_safe,
                                )

  # IMPORTANT: Ensure that we mark string as html_safe to avoid escaping.
  <<-HTML.html_safe
#{component_specification_tag}
#{rendered_output}
#{replay_console(options) ? console_script : ''}
  HTML
end

#sanitized_props_string(props) ⇒ Object



90
91
92
# File 'app/helpers/react_on_rails_helper.rb', line 90

def sanitized_props_string(props)
  props.is_a?(String) ? json_escape(props) : props.to_json
end

#server_render_js(js_expression, options = {}) ⇒ Object

Helper method to take javascript expression and returns the output from evaluating it. If you have more than one line that needs to be executed, wrap it in an IIFE. JS exceptions are caught and console messages are handled properly.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'app/helpers/react_on_rails_helper.rb', line 97

def server_render_js(js_expression, options = {})
  wrapper_js = <<-JS
(function() {
var htmlResult = '';
var consoleReplayScript = '';
var hasErrors = false;

try {
  htmlResult =
    (function() {
      return #{js_expression};
    })();
} catch(e) {
  htmlResult = ReactOnRails.handleError({e: e, name: null,
    jsCode: '#{escape_javascript(js_expression)}', serverSide: true});
  hasErrors = true;
}

consoleReplayScript = ReactOnRails.buildConsoleReplay();

return JSON.stringify({
    html: htmlResult,
    consoleReplayScript: consoleReplayScript,
    hasErrors: hasErrors
});

})()
  JS

  result = ReactOnRails::ServerRenderingPool.server_render_js_with_console_logging(wrapper_js)

  # IMPORTANT: To ensure that Rails doesn't auto-escape HTML tags, use the 'raw' method.
  html = result["html"]
  console_log_script = result["consoleLogScript"]
  raw("#{html}#{replay_console(options) ? console_log_script : ''}")
rescue ExecJS::ProgramError => err
  # rubocop:disable Style/RaiseArgs
  raise ReactOnRails::PrerenderError.new(component_name: "N/A (server_render_js called)",
                                         err: err,
                                         js_code: wrapper_js)
  # rubocop:enable Style/RaiseArgs
end