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??
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')),
)
})
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')),
)
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.