UPDATE: A new version of the Complete React on Rails Course is open for pre-orders. Get $10 Off Today.
The webpacker gem has given us an easy way to use JavaScript libraries, including React, inside Rails while using native JS tools like yarn and Webpack.
$ rails new myapp --webpack=react
$ ./bin/rails webpacker:install $ ./bin/rails webpacker:install:react
For example, in this calendar appointments app from my Free React on Rails course, we pass appointments data to a component called Appointments with the react_component method:
react_component(‘Appointments’, appointments: @appointments)

webpacker doesn’t provide any such convenience methods by default.
First let’s put the data as JSON inside the data attribute of a div in the view where we want to render the React component:
<%= content_tag :div, id: "appointments_data", data: @appointments.to_json do %> <% end %>
If you use HAML, you can simply write:
#appointments_data{data: @appointments.to_json}
document.addEventListener('DOMContentLoaded', () => { const node = document.getElementById('appointments_data') const data = JSON.parse(node.getAttribute('data')) ReactDOM.render( <Appointments appointments={data} />, document.body.appendChild(document.createElement('div')), ) })
UPDATE: A new version of the Complete React on Rails Course is open for pre-orders. Get $10 Off Today.
Comments