Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prerender a namespaced react component using the react-rails gem?

(Note: I'm using the 'therubyracer', 'react-rails', and 'sprockets-coffee-react' gems)

This is the code for my simple component (Hello.js.cjsx):

# @cjsx React.DOM

Hello = React.createClass(
  render: ->
    <div>
      Hello {@props.name || "World"}!
    </div>
)

window.components ?= {}
window.components.Hello = Hello

In my rails view (index.html.erb) this works just fine:

<%= render_component('components.Hello', {name: 'Jack'}) %>

However, when I try this:

<%= react_component('components.Hello', {name: 'Jill'}, {prerender: true}) %>

I get this error:

Encountered error "ReferenceError: components is not defined"

which seems odd because I'm defining it in my component.

What am I doing wrong?

like image 843
phaedryx Avatar asked Oct 21 '22 00:10

phaedryx


2 Answers

The problem is that for anything rendered with render_component it's required that the component is registered with the global window object. This is kind of not ideal but just how it works for the time being.

This is what I've been doing. Not ideal, but helps.

components /
    namespace /
       MyComponent.js.jsx

Then doing this in my file:

# components/namespace/MyComponent.js.jsx

window.NamespaceMyComponent = React.createClass({});

module.exports = window.NamespaceMyComponent;

This last part allows me to use browserify and require my module like this:

require('components/namespace/MyComponent')

and using the render_component helper like this:

<%= render_component "NamespaceMyComponent", {}, {prerender: true} %>

like image 182
Micah Avatar answered Oct 24 '22 11:10

Micah


I'm not sure about the syntax you used. Please, replace the lines :

window.components ?= {}
window.components.Hello = Hello

with

window.Hello = Hello

(You can follow this link for further examples).

like image 28
Zakaria Avatar answered Oct 24 '22 11:10

Zakaria