最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing data from rails controller to react component - Stack Overflow

programmeradmin3浏览0评论

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

Share Improve this question edited Jan 24, 2018 at 22:40 progmatico 4,9641 gold badge17 silver badges30 bronze badges asked Jan 24, 2018 at 21:56 SzalbikSzalbik 1332 silver badges10 bronze badges 4
  • 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
Add a ment  | 

2 Answers 2

Reset to default 11

Here 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')),
  )
})
发布评论

评论列表(0)

  1. 暂无评论