Module: ViteReact::ReactComponentHelper

Defined in:
lib/vite_react/railtie.rb,
lib/vite_react/railtie.rb

Instance Method Summary collapse

Instance Method Details

#react_component(name, file_name: nil, props: {}, options: {}, &block) ⇒ Object

Renders a React component with extended options.

Options:

- i18n: if true, merge current locale translations from Rails I18n YAML into props under :i18n.
- filename: if provided, used to determine the component file path on the Node server.

Example usage:

<%== react_component("MyComponent", file_name="CustomFile", props: { name: "Alice" }, options: { i18n: true }) %>


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/vite_react/railtie.rb', line 19

def react_component(name, props: {}, &block)
  if block_given?
    # SERVER‑SIDE RENDERING: capture block content
    children_html = capture(&block)
    # Merge in the children as a prop for your React component
    props_with_children = props.merge(children: children_html)
    ssr_html = render_react_component_ssr(name, props_with_children)
    ssr_html
  else
    # CLIENT‑SIDE RENDERING: output a placeholder div with data attributes
    placeholder_id = "react-component-#{SecureRandom.hex(8)}"
    (:div, "",
                id: placeholder_id,
                data: { react_component: name, props: props.to_json })
  end
end