Skip to content

Instantly share code, notes, and snippets.

@dcorrigan
Created April 19, 2017 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dcorrigan/efd67a58fdc7252ddf30931b8d8b5f4a to your computer and use it in GitHub Desktop.
Save dcorrigan/efd67a58fdc7252ddf30931b8d8b5f4a to your computer and use it in GitHub Desktop.
Rails 5.1 Webpacker with react_ujs from react-rails

Some quick notes about using Rails 5.1 webpacker gem for React integration and react_ujs to premount components.

For reference, react_ujs is the JS library from react-rails that renders React components with props. It expects a parent with data-react-class and data-react-props set. I don't remember my initial setup, but probably:

bundle exec rails new . --webpack=react --force
yarn add react_ujs

app/javascript/packs/hello_react.jsx

import React from 'react'
import ReactDOM from 'react-dom'
import ReactRailsUJS from 'react_ujs'

class Hello extends React.Component {
  render() {
    return <div>
      Hello {this.props.name}!
      <div className="bar">
        something else: {this.props.foo}
      </div>
    </div>
  }
}

export default Hello;
window.DanApp = {};
window.DanApp.Hello = Hello;

Then in any view:

<%= javascript_pack_tag 'hello_react' %>

<div data-react-class="DanApp.Hello" data-react-props="{&quot;name&quot;:&quot;dan&quot;,&quot;foo&quot;:&quot;bar&quot;}">
</div>

To use this for real, you would make a helper method to render the empty div and escape your JSON props. That view example is a very literal illustration of what ReactRailsUJS expects to find.

Including it in the component class file is not great. In reality, you'd include it as part of your regular JS bundle in the asset pipeline.

@dcorrigan
Copy link
Author

This probably doesn't have any advantages over just using the react-rails gem itself with webpacker integration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment