How do I import a JavaScript or JSX based component into React.rb so it is accessible in ruby?

237 Views Asked by At

Using the example given for React-Bootstrap and react.rb works perfectly but I am trying to get a NPN component called React-TimeAgo working and I am lost.

This is what I have done:

In index.js (for Webpack to import it into the webpack bundle):

window.bs = require('react-bootstrap')
window.timeago = require('react-timeago')

In the actual component.rb I have this:

class Rb < React::NativeLibrary
  imports 'bs'
end

class TimeAgo < React::NativeLibrary
  imports 'timeago'
end

Then referencing the Bootstrap components work perfectly:

Rb.Button(bsStyle: :primary) <- works as expected

But I am not managing to get anything out of the TimeAgo wrapper:

TimeAgo.new(date: "Aug 29, 2014") {} <- just does nothing
TimeAgo(date: "Aug 29, 2014") {}     <- method undefined

What am I doing wrong? All help appreciated!

1

There are 1 best solutions below

1
On

I found a workaround to this but it is not all that pretty. Would love to find a better solution!

class TimeAgo < React::Component::Base
   after_mount do
      `React.render(React.createElement(window.timeago,
        {date: 'apr 7, 2016'}),
        document.getElementById('something_unique')
       );`
   end

   def render
      span(id: "something_unique") { }
   end
 end

Of course you would need to ensure the id of the span is unique and you passed the date as a prop, but I left that out for brevity.