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="{"name":"dan","foo":"bar"}">
</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.
This probably doesn't have any advantages over just using the react-rails gem itself with webpacker integration.