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 ponent props. I have to do this by api or there is other way??
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 ponent props. I have to do this by api or there is other way??
- 1 Yep, according to pluralsight./guides/ruby-ruby-on-rails/… you need to create an api that you will hit from your React front-end. – Chase DeAnda Commented Jan 24, 2018 at 22:00
- You need to do it by API so you'll have to have two servers running. – Shirley Commented Jan 24, 2018 at 22:01
- While you do need to do it through an API, you definitely can acplish this using a single server. If you desire a separation of concerns, that's not a bad idea, but it's not necessary either. – Jake Haller-Roby Commented Jan 24, 2018 at 22:15
- If react is just V of MVC structure so there shouldn't be a way to pass data to ponent like passing to erb? – Szalbik Commented Jan 24, 2018 at 22:24
2 Answers
Reset to default 11Here is another way:
some_views.html.erb
<%= javascript_tag do %>
var appointments = <%= raw(@appointments.to_json) %>
<% end %>
some_react_ponents.js
document.addEventListener('DOMContentLoaded', () => {
const data = window.appointments
ReactDOM.render(
<Appointments appointments={data} />,
document.body.appendChild(document.createElement('div')),
)
})
I find solution by my self. https://hackernoon./how-to-get-your-rails-data-into-your-react-ponent-with-webpacker-647dc63706c9
By adding content tag to view where I want to render react ponent 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')),
)
})