5

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??

4
  • 1
    Yep, according to pluralsight.com/guides/ruby-ruby-on-rails/… you need to create an api that you will hit from your React front-end. Commented Jan 24, 2018 at 22:00
  • You need to do it by API so you'll have to have two servers running. Commented 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. 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 component like passing to erb? Commented Jan 24, 2018 at 22:24

2 Answers 2

11

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')),
  )
})
Sign up to request clarification or add additional context in comments.

Comments

3

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')),
  )
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.