Reputation: 133
I'm trying to integrate rails with react via webpacker, but i dont know how to pass in example @post = Post.all
from controller to react component props. I have to do this by api or there is other way??
Upvotes: 5
Views: 7163
Reputation: 44360
Here is another way:
some_views.html.erb
<%= javascript_tag do %>
var appointments = <%= raw(@appointments.to_json) %>
<% end %>
some_react_components.js
document.addEventListener('DOMContentLoaded', () => {
const data = window.appointments
ReactDOM.render(
<Appointments appointments={data} />,
document.body.appendChild(document.createElement('div')),
)
})
Upvotes: 11
Reputation: 133
I find solution by my self. https://hackernoon.com/how-to-get-your-rails-data-into-your-react-component-with-webpacker-647dc63706c9
By adding content tag to view where I want to render react component and pass props as attributes.
<%= content_tag :div,
id: "appointments_data",
data: @appointments.to_json do %>
<% end %>
then parse data and add it do props
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')),
)
})
Upvotes: 3