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??
-
1Yep, according to pluralsight.com/guides/ruby-ruby-on-rails/… you need to create an api that you will hit from your React front-end.Chase DeAnda– Chase DeAnda2018-01-24 22:00:10 +00:00Commented Jan 24, 2018 at 22:00
-
You need to do it by API so you'll have to have two servers running.Shirley– Shirley2018-01-24 22:01:12 +00:00Commented Jan 24, 2018 at 22:01
-
While you do need to do it through an API, you definitely can accomplish 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– Jake Haller-Roby2018-01-24 22:15:48 +00:00Commented 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 component like passing to erb?Szalbik– Szalbik2018-01-24 22:24:19 +00:00Commented Jan 24, 2018 at 22:24
Add a comment
|
2 Answers
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')),
)
})
Comments
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')),
)
})