Module: ReactOnRails::Helper
- Includes:
- Pro::Helper, Utils::Required, ScoutApm::Tracer
- Included in:
- ReactOnRailsHelper
- Defined in:
- lib/react_on_rails/helper.rb
Constant Summary collapse
- COMPONENT_HTML_KEY =
"componentHtml"
Constants included from Pro::Helper
Pro::Helper::IMMEDIATE_HYDRATION_PRO_WARNING
Instance Method Summary collapse
- #build_react_component_result_for_server_rendered_hash(server_rendered_html: required("server_rendered_html"), component_specification_tag: required("component_specification_tag"), console_script: required("console_script"), render_options: required("render_options")) ⇒ Object
- #build_react_component_result_for_server_rendered_string(server_rendered_html: required("server_rendered_html"), component_specification_tag: required("component_specification_tag"), console_script: required("console_script"), render_options: required("render_options")) ⇒ Object
- #build_react_component_result_for_server_streamed_content(rendered_html_stream:, component_specification_tag:, render_options:) ⇒ Object
- #compose_react_component_html_with_spec_and_console(component_specification_tag, rendered_output, console_script) ⇒ Object
- #create_render_options(react_component_name, options) ⇒ Object
- #generated_components_pack_path(component_name) ⇒ Object
- #in_mailer? ⇒ Boolean
- #initialize_redux_stores(render_options) ⇒ Object
- #internal_react_component(react_component_name, options = {}) ⇒ Object
- #internal_rsc_payload_react_component(react_component_name, options = {}) ⇒ Object
- #internal_stream_react_component(component_name, options = {}) ⇒ Object
- #json_safe_and_pretty(hash_or_string) ⇒ Object
- #load_pack_for_generated_component(react_component_name, render_options) ⇒ Object
-
#prepend_render_rails_context(render_value) ⇒ Object
prepend the rails_context if not yet applied.
- #props_string(props) ⇒ Object
-
#rails_context(server_side: true) ⇒ Object
This is the definitive list of the default values used for the rails_context, which is the second parameter passed to both component and store Render-Functions.
- #rails_context_if_not_already_rendered ⇒ Object
- #raise_missing_autoloaded_bundle(react_component_name) ⇒ Object
- #raise_prerender_error(json_result, react_component_name, props, js_code) ⇒ Object
-
#react_component(component_name, options = {}) ⇒ Object
react_component_name: can be a React function or class component or a “Render-Function”.
-
#react_component_hash(component_name, options = {}) ⇒ Object
react_component_hash is used to return multiple HTML strings for server rendering, such as for adding meta-tags to a page.
-
#redux_store(store_name, props: {}, defer: false, immediate_hydration: nil) ⇒ Object
Separate initialization of store from react_component allows multiple react_component calls to use the same Redux store.
-
#redux_store_hydration_data ⇒ Object
Place this view helper (no parameters) at the end of your shared layout.
- #registered_stores ⇒ Object
- #registered_stores_defer_render ⇒ Object
- #registered_stores_including_deferred ⇒ Object
- #render_redux_store_data(redux_store_data) ⇒ Object
- #replay_console_option(val) ⇒ Object
-
#rsc_payload_react_component(component_name, options = {}) ⇒ String
Renders the React Server Component (RSC) payload for a given component.
-
#run_stream_inside_fiber ⇒ Object
rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity.
- #sanitized_props_string(props) ⇒ Object
-
#server_render_js(js_expression, options = {}) ⇒ Object
Helper method to take javascript expression and returns the output from evaluating it.
-
#server_rendered_react_component(render_options) ⇒ Object
Returns object with values that are NOT html_safe!.
- #should_raise_streaming_prerender_error?(chunk_json_result, render_options) ⇒ Boolean
-
#stream_react_component(component_name, options = {}) ⇒ Object
Streams a server-side rendered React component using React’s ‘renderToPipeableStream`.
Methods included from Pro::Helper
#disabled_pro_features_message, #generate_component_script, #generate_store_script, #pro_warning_badge_if_needed
Methods included from Utils::Required
Instance Method Details
#build_react_component_result_for_server_rendered_hash(server_rendered_html: required("server_rendered_html"), component_specification_tag: required("component_specification_tag"), console_script: required("console_script"), render_options: required("render_options")) ⇒ Object
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 |
# File 'lib/react_on_rails/helper.rb', line 573 def build_react_component_result_for_server_rendered_hash( server_rendered_html: required("server_rendered_html"), component_specification_tag: required("component_specification_tag"), console_script: required("console_script"), render_options: required("render_options") ) = . [:id] = .dom_id unless server_rendered_html[COMPONENT_HTML_KEY] raise ReactOnRails::Error, "server_rendered_html hash expected to contain \"#{COMPONENT_HTML_KEY}\" key." end rendered_output = content_tag(:div, server_rendered_html[COMPONENT_HTML_KEY].html_safe, ) result_console_script = .replay_console ? console_script : "" result = compose_react_component_html_with_spec_and_console( component_specification_tag, rendered_output, result_console_script ) # Other HTML strings need to be marked as html_safe too: server_rendered_hash_except_component = server_rendered_html.except(COMPONENT_HTML_KEY) server_rendered_hash_except_component.each do |key, html_string| server_rendered_hash_except_component[key] = html_string.html_safe end result_with_rails_context = prepend_render_rails_context(result) { COMPONENT_HTML_KEY => result_with_rails_context }.merge( server_rendered_hash_except_component ) end |
#build_react_component_result_for_server_rendered_string(server_rendered_html: required("server_rendered_html"), component_specification_tag: required("component_specification_tag"), console_script: required("console_script"), render_options: required("render_options")) ⇒ Object
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 |
# File 'lib/react_on_rails/helper.rb', line 520 def build_react_component_result_for_server_rendered_string( server_rendered_html: required("server_rendered_html"), component_specification_tag: required("component_specification_tag"), console_script: required("console_script"), render_options: required("render_options") ) = . if .key?(:tag) = [:tag] .delete(:tag) else = "div" end [:id] = .dom_id rendered_output = content_tag(.to_sym, server_rendered_html.html_safe, ) result_console_script = .replay_console ? console_script : "" result = compose_react_component_html_with_spec_and_console( component_specification_tag, rendered_output, result_console_script ) prepend_render_rails_context(result) end |
#build_react_component_result_for_server_streamed_content(rendered_html_stream:, component_specification_tag:, render_options:) ⇒ Object
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 |
# File 'lib/react_on_rails/helper.rb', line 547 def build_react_component_result_for_server_streamed_content( rendered_html_stream:, component_specification_tag:, render_options: ) is_first_chunk = true rendered_html_stream.transform do |chunk_json_result| if is_first_chunk is_first_chunk = false build_react_component_result_for_server_rendered_string( server_rendered_html: chunk_json_result["html"], component_specification_tag: component_specification_tag, console_script: chunk_json_result["consoleReplayScript"], render_options: ) else result_console_script = .replay_console ? chunk_json_result["consoleReplayScript"] : "" # No need to prepend component_specification_tag or add rails context again # as they're already included in the first chunk compose_react_component_html_with_spec_and_console( "", chunk_json_result["html"], result_console_script ) end end end |
#compose_react_component_html_with_spec_and_console(component_specification_tag, rendered_output, console_script) ⇒ Object
607 608 609 610 611 612 613 614 |
# File 'lib/react_on_rails/helper.rb', line 607 def compose_react_component_html_with_spec_and_console(component_specification_tag, rendered_output, console_script) # IMPORTANT: Ensure that we mark string as html_safe to avoid escaping. added_html = "#{component_specification_tag}\n#{console_script}".strip added_html = added_html.present? ? "\n#{added_html}" : "" "#{rendered_output}#{added_html}".html_safe end |
#create_render_options(react_component_name, options) ⇒ Object
487 488 489 490 491 492 493 494 495 |
# File 'lib/react_on_rails/helper.rb', line 487 def (react_component_name, ) # If no store dependencies are passed, default to all registered stores up till now unless .key?(:store_dependencies) store_dependencies = registered_stores_including_deferred.map { |store| store[:store_name] } = .merge(store_dependencies: store_dependencies.presence) end ReactOnRails::ReactComponent::RenderOptions.new(react_component_name: react_component_name, options: ) end |
#generated_components_pack_path(component_name) ⇒ Object
516 517 518 |
# File 'lib/react_on_rails/helper.rb', line 516 def generated_components_pack_path(component_name) "#{ReactOnRails::PackerUtils.packer_source_entry_path}/generated/#{component_name}.js" end |
#in_mailer? ⇒ Boolean
782 783 784 785 786 787 |
# File 'lib/react_on_rails/helper.rb', line 782 def in_mailer? return false unless defined?(controller) return false unless defined?(ActionMailer::Base) controller.is_a?(ActionMailer::Base) end |
#initialize_redux_stores(render_options) ⇒ Object
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 |
# File 'lib/react_on_rails/helper.rb', line 752 def initialize_redux_stores() result = +<<-JS ReactOnRails.clearHydratedStores(); JS store_dependencies = .store_dependencies return result unless store_dependencies.present? declarations = +"var reduxProps, store, storeGenerator;\n" store_objects = registered_stores_including_deferred.select do |store| store_dependencies.include?(store[:store_name]) end result << store_objects.each_with_object(declarations) do |redux_store_data, memo| store_name = redux_store_data[:store_name] props = props_string(redux_store_data[:props]) memo << <<-JS.strip_heredoc reduxProps = #{props}; storeGenerator = ReactOnRails.getStoreGenerator('#{store_name}'); store = storeGenerator(reduxProps, railsContext); ReactOnRails.setStore('#{store_name}', store); JS end result end |
#internal_react_component(react_component_name, options = {}) ⇒ Object
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 |
# File 'lib/react_on_rails/helper.rb', line 636 def internal_react_component(react_component_name, = {}) # 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. = (react_component_name, ) # 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. component_specification_tag = generate_component_script() load_pack_for_generated_component(react_component_name, ) # Create the HTML rendering part result = server_rendered_react_component() { render_options: , tag: component_specification_tag, result: result } end |
#internal_rsc_payload_react_component(react_component_name, options = {}) ⇒ Object
507 508 509 510 511 512 513 514 |
# File 'lib/react_on_rails/helper.rb', line 507 def internal_rsc_payload_react_component(react_component_name, = {}) = .merge(render_mode: :rsc_payload_streaming) = (react_component_name, ) json_stream = server_rendered_react_component() json_stream.transform do |chunk| "#{chunk.to_json}\n".html_safe end end |
#internal_stream_react_component(component_name, options = {}) ⇒ Object
497 498 499 500 501 502 503 504 505 |
# File 'lib/react_on_rails/helper.rb', line 497 def internal_stream_react_component(component_name, = {}) = .merge(render_mode: :html_streaming) result = internal_react_component(component_name, ) build_react_component_result_for_server_streamed_content( rendered_html_stream: result[:result], component_specification_tag: result[:tag], render_options: result[:render_options] ) end |
#json_safe_and_pretty(hash_or_string) ⇒ Object
350 351 352 353 354 355 356 357 358 359 360 361 |
# File 'lib/react_on_rails/helper.rb', line 350 def json_safe_and_pretty(hash_or_string) return "{}" if hash_or_string.nil? unless hash_or_string.is_a?(String) || hash_or_string.is_a?(Hash) raise ReactOnRails::Error, "#{__method__} only accepts String or Hash as argument " \ "(#{hash_or_string.class} given)." end json_value = hash_or_string.is_a?(String) ? hash_or_string : hash_or_string.to_json ReactOnRails::JsonOutput.escape(json_value) end |
#load_pack_for_generated_component(react_component_name, render_options) ⇒ Object
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 |
# File 'lib/react_on_rails/helper.rb', line 429 def load_pack_for_generated_component(react_component_name, ) return unless .auto_load_bundle ReactOnRails::PackerUtils.raise_nested_entries_disabled unless ReactOnRails::PackerUtils.nested_entries? if Rails.env.development? is_component_pack_present = File.exist?(generated_components_pack_path(react_component_name)) raise_missing_autoloaded_bundle(react_component_name) unless is_component_pack_present end = { defer: ReactOnRails.configuration.generated_component_packs_loading_strategy == :defer } # Old versions of Shakapacker don't support async script tags. # ReactOnRails.configure already validates if async loading is supported by the installed Shakapacker version. # Therefore, we only need to pass the async option if the loading strategy is explicitly set to :async [:async] = true if ReactOnRails.configuration.generated_component_packs_loading_strategy == :async append_javascript_pack_tag("generated/#{react_component_name}", **) append_stylesheet_pack_tag("generated/#{react_component_name}") end |
#prepend_render_rails_context(render_value) ⇒ Object
prepend the rails_context if not yet applied
630 631 632 633 634 |
# File 'lib/react_on_rails/helper.rb', line 630 def prepend_render_rails_context(render_value) rails_context_content = rails_context_if_not_already_rendered rails_context_content = rails_context_content.present? ? "#{rails_context_content}\n" : "" "#{rails_context_content}#{render_value}".html_safe end |
#props_string(props) ⇒ Object
667 668 669 |
# File 'lib/react_on_rails/helper.rb', line 667 def props_string(props) props.is_a?(String) ? props : props.to_json end |
#rails_context(server_side: true) ⇒ Object
This is the definitive list of the default values used for the rails_context, which is the second parameter passed to both component and store Render-Functions. This method can be called from views and from the controller, as ‘helpers.rails_context`
rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 |
# File 'lib/react_on_rails/helper.rb', line 368 def rails_context(server_side: true) # ALERT: Keep in sync with node_package/src/types/index.ts for the properties of RailsContext @rails_context ||= begin result = { componentRegistryTimeout: ReactOnRails.configuration.component_registry_timeout, railsEnv: Rails.env, inMailer: in_mailer?, # Locale settings i18nLocale: I18n.locale, i18nDefaultLocale: I18n.default_locale, rorVersion: ReactOnRails::VERSION, # TODO: v13 just use the version if existing rorPro: ReactOnRails::Utils.react_on_rails_pro? } if ReactOnRails::Utils.react_on_rails_pro? result[:rorProVersion] = ReactOnRails::Utils.react_on_rails_pro_version if ReactOnRails::Utils.rsc_support_enabled? rsc_payload_url = ReactOnRailsPro.configuration.rsc_payload_generation_url_path result[:rscPayloadGenerationUrlPath] = rsc_payload_url end end if defined?(request) && request.present? # Check for encoding of the request's original_url and try to force-encoding the # URLs as UTF-8. This situation can occur in browsers that do not encode the # entire URL as UTF-8 already, mostly on the Windows platform (IE11 and lower). original_url_normalized = request.original_url if original_url_normalized.encoding == Encoding::BINARY original_url_normalized = original_url_normalized.force_encoding(Encoding::ISO_8859_1) .encode(Encoding::UTF_8) end # Using Addressable instead of standard URI to better deal with # non-ASCII characters (see https://github.com/shakacode/react_on_rails/pull/405) uri = Addressable::URI.parse(original_url_normalized) # uri = Addressable::URI.parse("http://foo.com:3000/posts?id=30&limit=5#time=1305298413") result.merge!( # URL settings href: uri.to_s, location: "#{uri.path}#{"?#{uri.query}" if uri.query.present?}", scheme: uri.scheme, # http host: uri.host, # foo.com port: uri.port, pathname: uri.path, # /posts search: uri.query, # id=30&limit=5 httpAcceptLanguage: request.env["HTTP_ACCEPT_LANGUAGE"] ) end if ReactOnRails.configuration.rendering_extension custom_context = ReactOnRails.configuration.rendering_extension.custom_context(self) result.merge!(custom_context) if custom_context end result end @rails_context.merge(serverSide: server_side) end |
#rails_context_if_not_already_rendered ⇒ Object
616 617 618 619 620 621 622 623 624 625 626 627 |
# File 'lib/react_on_rails/helper.rb', line 616 def rails_context_if_not_already_rendered return "" if @rendered_rails_context data = rails_context(server_side: false) @rendered_rails_context = true content_tag(:script, json_safe_and_pretty(data).html_safe, type: "application/json", id: "js-react-on-rails-context") end |
#raise_missing_autoloaded_bundle(react_component_name) ⇒ Object
796 797 798 799 800 801 802 803 804 805 |
# File 'lib/react_on_rails/helper.rb', line 796 def raise_missing_autoloaded_bundle(react_component_name) msg = <<~MSG **ERROR** ReactOnRails: Component "#{react_component_name}" is configured as "auto_load_bundle: true" but the generated component entrypoint, which should have been at #{generated_components_pack_path(react_component_name)}, is missing. You might want to check that this component is in a directory named "#{ReactOnRails.configuration.components_subdirectory}" & that "bundle exec rake react_on_rails:generate_packs" has been run. MSG raise ReactOnRails::Error, msg end |
#raise_prerender_error(json_result, react_component_name, props, js_code) ⇒ Object
671 672 673 674 675 676 677 678 679 |
# File 'lib/react_on_rails/helper.rb', line 671 def raise_prerender_error(json_result, react_component_name, props, js_code) raise ReactOnRails::PrerenderError.new( component_name: react_component_name, props: sanitized_props_string(props), err: nil, js_code: js_code, console_messages: json_result["consoleReplayScript"] ) end |
#react_component(component_name, options = {}) ⇒ Object
react_component_name: can be a React function or class component or a “Render-Function”. “Render-Functions” differ from a React function in that they take two parameters, the
props and the railsContext, like this:
let MyReactComponentApp = (props, railsContext) => <MyReactComponent {...props}/>;
Alternately, you can define the Render-Function with an additional property
`.renderFunction = true`:
let MyReactComponentApp = (props) => <MyReactComponent {...props}/>;
MyReactComponent.renderFunction = true;
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/packs/server-bundle.js and
spec/dummy/client/app/packs/client-bundle.js for examples of this.
options:
props: Ruby Hash or JSON string which contains the properties to pass to the react object. Do
not pass any props if you are separately initializing the store by the `redux_store` helper.
prerender: <true/false> set to false when debugging!
id: You can optionally set the id, or else a unique one is automatically generated.
html_options: You can set other html attributes that will go on this component
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. random_dom_id can be set to override the default from the config/initializers. That’s only used if you have multiple instance of the same component on the Rails view.
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 89 90 91 92 93 94 95 |
# File 'lib/react_on_rails/helper.rb', line 58 def react_component(component_name, = {}) internal_result = internal_react_component(component_name, ) server_rendered_html = internal_result[:result]["html"] console_script = internal_result[:result]["consoleReplayScript"] = internal_result[:render_options] case server_rendered_html when String html = build_react_component_result_for_server_rendered_string( server_rendered_html: server_rendered_html, component_specification_tag: internal_result[:tag], console_script: console_script, render_options: ) html.html_safe when Hash msg = <<~MSG Use react_component_hash (not react_component) to return a Hash to your ruby view code. See https://github.com/shakacode/react_on_rails/blob/master/spec/dummy/client/app/startup/ReactHelmetServerApp.jsx for an example of the necessary javascript configuration. MSG raise ReactOnRails::Error, msg else class_name = server_rendered_html.class.name msg = <<~MSG ReactOnRails: server_rendered_html is expected to be a String or Hash for #{component_name}. Type is #{class_name} Value: #{server_rendered_html} If you're trying to use a Render-Function to return a Hash to your ruby view code, then use react_component_hash instead of react_component and see https://github.com/shakacode/react_on_rails/blob/master/spec/dummy/client/app/startup/ReactHelmetServerApp.jsx for an example of the JavaScript code. MSG raise ReactOnRails::Error, msg end end |
#react_component_hash(component_name, options = {}) ⇒ Object
react_component_hash is used to return multiple HTML strings for server rendering, such as for adding meta-tags to a page. It is exactly like react_component except for the following:
-
prerender: true is automatically added, as this method doesn’t make sense for client only rendering.
-
Your JavaScript Render-Function for server rendering must return an Object rather than a React component.
-
Your view code must expect an object and not a string.
Here is an example of the view code:
<% react_helmet_app = react_component_hash("ReactHelmetApp", prerender: true,
props: { helloWorldData: { name: "Mr. Server Side Rendering"}},
id: "react-helmet-0", trace: true) %>
<% content_for :title do %>
<%= react_helmet_app['title'] %>
<% end %>
<%= react_helmet_app["componentHtml"] %>
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
# File 'lib/react_on_rails/helper.rb', line 212 def react_component_hash(component_name, = {}) [:prerender] = true internal_result = internal_react_component(component_name, ) server_rendered_html = internal_result[:result]["html"] console_script = internal_result[:result]["consoleReplayScript"] = internal_result[:render_options] if server_rendered_html.is_a?(String) && internal_result[:result]["hasErrors"] server_rendered_html = { COMPONENT_HTML_KEY => internal_result[:result]["html"] } end if server_rendered_html.is_a?(Hash) build_react_component_result_for_server_rendered_hash( server_rendered_html: server_rendered_html, component_specification_tag: internal_result[:tag], console_script: console_script, render_options: ) else msg = <<~MSG Render-Function used by react_component_hash for #{component_name} is expected to return an Object. See https://github.com/shakacode/react_on_rails/blob/master/spec/dummy/client/app/startup/ReactHelmetServerApp.jsx for an example of the JavaScript code. Note, your Render-Function must either take 2 params or have the property `.renderFunction = true` added to it to distinguish it from a React Function Component. MSG raise ReactOnRails::Error, msg end end |
#redux_store(store_name, props: {}, defer: false, immediate_hydration: nil) ⇒ Object
Separate initialization of store from react_component allows multiple react_component calls to use the same Redux store.
NOTE: This technique not recommended as it prevents dynamic code splitting for performance. Instead, you should use the standard react_component view helper.
store_name: name of the store, corresponding to your call to ReactOnRails.registerStores in your
JavaScript code.
props: Ruby Hash or JSON string which contains the properties to pass to the redux store. Options
defer: false -- pass as true if you wish to render this below your component.
immediate_hydration: false -- React on Rails Pro (licensed) feature. Pass as true if you wish to
hydrate this store immediately instead of waiting for the page to load.
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 |
# File 'lib/react_on_rails/helper.rb', line 257 def redux_store(store_name, props: {}, defer: false, immediate_hydration: nil) immediate_hydration = ReactOnRails.configuration.immediate_hydration if immediate_hydration.nil? redux_store_data = { store_name: store_name, props: props, immediate_hydration: immediate_hydration } if defer registered_stores_defer_render << redux_store_data "YOU SHOULD NOT SEE THIS ON YOUR VIEW -- Uses as a code block, like <% redux_store %> " \ "and not <%= redux store %>" else registered_stores << redux_store_data result = render_redux_store_data(redux_store_data) prepend_render_rails_context(result).html_safe end end |
#redux_store_hydration_data ⇒ Object
Place this view helper (no parameters) at the end of your shared layout. This tell ReactOnRails where to client render the redux store hydration data. Since we’re going to be setting up the stores in the controllers, we need to know where on the view to put the client side rendering of this hydration data, which is a hidden div with a matching class that contains a data props.
279 280 281 282 283 284 285 |
# File 'lib/react_on_rails/helper.rb', line 279 def redux_store_hydration_data return if registered_stores_defer_render.blank? registered_stores_defer_render.reduce(+"") do |accum, redux_store_data| accum << render_redux_store_data(redux_store_data) end.html_safe end |
#registered_stores ⇒ Object
475 476 477 |
# File 'lib/react_on_rails/helper.rb', line 475 def registered_stores @registered_stores ||= [] end |
#registered_stores_defer_render ⇒ Object
479 480 481 |
# File 'lib/react_on_rails/helper.rb', line 479 def registered_stores_defer_render @registered_stores_defer_render ||= [] end |
#registered_stores_including_deferred ⇒ Object
483 484 485 |
# File 'lib/react_on_rails/helper.rb', line 483 def registered_stores_including_deferred registered_stores + registered_stores_defer_render end |
#render_redux_store_data(redux_store_data) ⇒ Object
661 662 663 664 665 |
# File 'lib/react_on_rails/helper.rb', line 661 def render_redux_store_data(redux_store_data) store_hydration_data = generate_store_script(redux_store_data) prepend_render_rails_context(store_hydration_data) end |
#replay_console_option(val) ⇒ Object
778 779 780 |
# File 'lib/react_on_rails/helper.rb', line 778 def replay_console_option(val) val.nil? ? ReactOnRails.configuration.replay_console : val end |
#rsc_payload_react_component(component_name, options = {}) ⇒ String
This helper requires React Server Components support to be enabled in your configuration: ReactOnRailsPro.configure do |config|
config.enable_rsc_support = true
end
You don’t have to deal directly with this helper function - it’s used internally by the
Renders the React Server Component (RSC) payload for a given component. This helper generates a special format designed by React for serializing server components and transmitting them to the client.
Example NDJSON stream:
{"html":"<RSC Payload>","consoleReplayScript":"","hasErrors":false,"isShellReady":true}
{"html":"<RSC Payload>","consoleReplayScript":"console.log('Loading...')","hasErrors":false,"isShellReady":true}
The RSC payload within the html field contains:
-
The component’s rendered output from the server
-
References to client components that need hydration
-
Data props passed to client components
‘rsc_payload_route` helper function. The returned data from this function is used internally by components registered using the `registerServerComponent` function. Don’t use it unless you need more control over the RSC payload generation. To know more about RSC payload, see the following link:
186 187 188 189 190 191 192 193 |
# File 'lib/react_on_rails/helper.rb', line 186 def rsc_payload_react_component(component_name, = {}) # rsc_payload_react_component doesn't have the prerender option # Because setting prerender to false will not do anything [:prerender] = true run_stream_inside_fiber do internal_rsc_payload_react_component(component_name, ) end end |
#run_stream_inside_fiber ⇒ Object
rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 |
# File 'lib/react_on_rails/helper.rb', line 449 def run_stream_inside_fiber unless ReactOnRails::Utils.react_on_rails_pro? raise ReactOnRails::Error, "You must use React on Rails Pro to use the stream_react_component method." end if @rorp_rendering_fibers.nil? raise ReactOnRails::Error, "You must call stream_view_containing_react_components to render the view containing the react component" end rendering_fiber = Fiber.new do stream = yield stream.each_chunk do |chunk| Fiber.yield chunk end end @rorp_rendering_fibers << rendering_fiber # return the first chunk of the fiber # It contains the initial html of the component # all updates will be appended to the stream sent to browser rendering_fiber.resume end |
#sanitized_props_string(props) ⇒ Object
287 288 289 |
# File 'lib/react_on_rails/helper.rb', line 287 def sanitized_props_string(props) ReactOnRails::JsonOutput.escape(props.is_a?(String) ? 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. Options include:{ prerender:, trace:, raise_on_prerender_error:, throw_js_errors: }
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 |
# File 'lib/react_on_rails/helper.rb', line 295 def server_render_js(js_expression, = {}) = ReactOnRails::ReactComponent::RenderOptions .new(react_component_name: "generic-js", options: ) js_code = <<-JS.strip_heredoc (function() { var htmlResult = ''; var consoleReplayScript = ''; var hasErrors = false; var renderingError = null; var renderingErrorObject = {}; try { htmlResult = (function() { return #{js_expression}; })(); } catch(e) { renderingError = e; if (#{.throw_js_errors}) { throw e; } htmlResult = ReactOnRails.handleError({e: e, name: null, jsCode: '#{escape_javascript(js_expression)}', serverSide: true}); hasErrors = true; renderingErrorObject = { message: renderingError.message, stack: renderingError.stack, } } consoleReplayScript = ReactOnRails.buildConsoleReplay(); return JSON.stringify({ html: htmlResult, consoleReplayScript: consoleReplayScript, hasErrors: hasErrors, renderingError: renderingErrorObject }); })() JS result = ReactOnRails::ServerRenderingPool .server_render_js_with_console_logging(js_code, ) html = result["html"] console_log_script = result["consoleLogScript"] raw("#{html}#{console_log_script if .replay_console}") rescue ExecJS::ProgramError => err raise ReactOnRails::PrerenderError.new(component_name: "N/A (server_render_js called)", err: err, js_code: js_code) end |
#server_rendered_react_component(render_options) ⇒ Object
Returns object with values that are NOT html_safe!
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 |
# File 'lib/react_on_rails/helper.rb', line 691 def server_rendered_react_component() return { "html" => "", "consoleReplayScript" => "" } unless .prerender react_component_name = .react_component_name props = .props # On server `location` option is added (`location = request.fullpath`) # React Router needs this to match the current route # Make sure that we use up-to-date bundle file used for server rendering, which is defined # by config file value for config.server_bundle_js_file ReactOnRails::ServerRenderingPool.reset_pool_if_server_bundle_was_modified # Since this code is not inserted on a web page, we don't need to escape props # # However, as JSON (returned from `props_string(props)`) isn't JavaScript, # but we want treat it as such, we need to compensate for the difference. # # \u2028 and \u2029 are valid characters in strings in JSON, but are treated # as newline separators in JavaScript. As no newlines are allowed in # strings in JavaScript, this causes an exception. # # We fix this by replacing these unicode characters with their escaped versions. # This should be safe, as the only place they can appear is in strings anyway. # # Read more here: http://timelessrepo.com/json-isnt-a-javascript-subset js_code = ReactOnRails::ServerRenderingJsCode.server_rendering_component_js_code( props_string: props_string(props).gsub("\u2028", '\u2028').gsub("\u2029", '\u2029'), rails_context: rails_context(server_side: true).to_json, redux_stores: initialize_redux_stores(), react_component_name: react_component_name, render_options: ) begin result = ReactOnRails::ServerRenderingPool.server_render_js_with_console_logging(js_code, ) rescue StandardError => err # This error came from the renderer raise ReactOnRails::PrerenderError.new(component_name: react_component_name, # Sanitize as this might be browser logged props: sanitized_props_string(props), err: err, js_code: js_code) end if .streaming? result.transform do |chunk_json_result| if should_raise_streaming_prerender_error?(chunk_json_result, ) raise_prerender_error(chunk_json_result, react_component_name, props, js_code) end # It doesn't make any transformation, it listens and raises error if a chunk has errors chunk_json_result end elsif result["hasErrors"] && .raise_on_prerender_error raise_prerender_error(result, react_component_name, props, js_code) end result end |
#should_raise_streaming_prerender_error?(chunk_json_result, render_options) ⇒ Boolean
681 682 683 684 685 686 687 688 |
# File 'lib/react_on_rails/helper.rb', line 681 def should_raise_streaming_prerender_error?(chunk_json_result, ) chunk_json_result["hasErrors"] && (if chunk_json_result["isShellReady"] .raise_non_shell_server_rendering_errors else .raise_on_prerender_error end) end |
#stream_react_component(component_name, options = {}) ⇒ Object
Streams a server-side rendered React component using React’s ‘renderToPipeableStream`. Supports React 18 features like Suspense, concurrent rendering, and selective hydration. Enables progressive rendering and improved performance for large components.
Note: This function can only be used with React on Rails Pro. The view that uses this function must be rendered using the ‘stream_view_containing_react_components` method from the React on Rails Pro gem.
Example of an async React component that can benefit from streaming:
const AsyncComponent = async () =>
const data = await fetchData();
return <div>{data</div>;
};
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<AsyncComponent />
</Suspense>
);
}
Any other options are passed to the content tag, including the id.
128 129 130 131 132 133 134 135 136 |
# File 'lib/react_on_rails/helper.rb', line 128 def stream_react_component(component_name, = {}) # stream_react_component doesn't have the prerender option # Because setting prerender to false is equivalent to calling react_component with prerender: false [:prerender] = true = .merge(immediate_hydration: true) unless .key?(:immediate_hydration) run_stream_inside_fiber do internal_stream_react_component(component_name, ) end end |