Search code examples
ruby-on-railsreactjsreact-rails

How do you reference 3rd party react components in a Rails app?


I'm building an app using the react-rails gem. This means all assets flow through the rails asset pipeline. In order to access 3rd party javascript libraries, I've been taking advantage of rails-assets.org which bundles javascript packages from bower into your rails environment. Most packages can just be called directly in your javascript code.

So if you add package, take marked the markdown library, you include it like:

gem 'rails-assets-marked', source: 'https://rails-assets.org'

And then can easily call it from any js file in your rails app like:

console.log(marked('I am using __markdown__.'));

However, how do you use packages which are not functions but instead are react components? In a node app, you'd use require() like below. Here's an example with react-clipboard:

var Clipboard = require("react-clipboard");

var App = React.createClass({

  render: function() {

    return (
      <div>
        <Clipboard value='some value' onCopy={some function} />
      </div>
    );
  },

But, what do you do to accomplish this in a Rails app?

Even though the package is included in the rails asset pipeline, the react component Clipboard isn't available in JSX. How does one make it available?


Solution

  • There is no way to accomplish this directly using rails only.

    To be able to use require("react-clipboard"), one solution (the less intrusive) would be to use a combination of rails, react-rails and browserify as explained here:

    http://collectiveidea.com/blog/archives/2016/04/13/rails-react-npm-without-the-pain/

    and here

    https://gist.github.com/oelmekki/c78cfc8ed1bba0da8cee

    I did not re paste the whole code example as it is rather long and prone to changes in the future