Search code examples
jqueryrubyopalrbreact.rb

Trying to get react.rb template to render in opal using opal-jquery, was working now it's not


I admit this is similar to a previous question of mine but it's not quite the same. Since I'm using ajax requests in the end I decided to add opal-jquery to my stack, (unless you know an easier way) and switched to using the Document.ready? function provided by it.

My function now looks like this:

def render_component component,mount_point
   React.render React.create_element(component), Element.find[mount_point][0]
end

and I call it like this:

Document.ready? do
    render_component LoginForm, '#view_port'
end

The problem is that before this was working and now, it's not, I'm getting an Uncaught NoMethodError: undefined method '[]' for nil error, it was working and then it just suddenly started doing this.

The error is because for some reason Element.find[mount_point] is returning nil and I don't know why. It should be running after the dom is loaded so the mount point '#view_port' should exist; it definitely exists in the dom as you can see here:

<body>
  <section id="main">
    <section id="view_port">  
    </section>
  </section>

<div class="hiddendiv common"></div>
</body>

I've even tried wrapping it in window.addEventListener("load", function () {} but to no effect.

Why is it now not working? what have I missed?


Solution

  • OK, The problem is that the Element['#view_port'] inside the render_component function was being called before Document.ready? and so was returning nil. Why this was I don't know, It should work, but it wasn't, so there you go.

    Another problem which is worth mentioning (slightly related) was that trying Element['#view_port'][0] to get the native object results in the error Uncaught TypeError: b.toLowerCase is not a function so you can't use Jquery to get native dom elements, which means your stuck with document.getElementById('view_port').