(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?
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} %>
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With