2

How do you call a Rails 5.1 database object into a React component?

For example, in a standard Rails view, I can call an object using @object assuming I have access to it configured in the controller.

With Rails 5.1, using the Webpacker enabled React functionality, how do I call a Rails database object into a React component?

I want to map through all the @objects in my database in a React component.

With the react-rails gem, you can use something like this to access those objects in your jsx file:

 <%= react_component('Component', props: @objects) %>

How do I do something similar without using the gem and just using the base Rails 5.1/Webpacker React setup?

My understanding is it uses a ruby tag like this:

<%= javascript_pack_tag "Component" %>
JohnOHFS
  • 174
  • 14

1 Answers1

3

In the view template where you want to render the React component:

<%= javascript_pack_tag 'Component' %>

<%= content_tag :div,
  id: 'objects_data',
  data: @objects.to_json do %>
<% end %>

This renders this html tag

<div id="objects_data" data="[{"id": 1, "created_at": .....}]"></div>

Then in your JS file

document.addEventListener('DOMContentLoaded', () => {
  var objectsDataTag = document.getElementById('objects_data')
  const objectsData = JSON.parse(objectsDataTag.getAttribute('data'))
})

Now you have your JSON data stored in the objectsData constant.

My understanding is that this is how <%= react_component('Component', props: @objects) %> works as well.

This is covered in a bit more detail in the webpacker docs and in this blog post

m. simon borg
  • 2,515
  • 12
  • 20
  • Thanks! I'll try that. – JohnOHFS Aug 15 '17 at 14:03
  • @JohnOHFS I just added an update showing that the JSON parsing should be wrapped in a DOM loading event listener, and also added a link to a blog post that helped me figure it out for my own project. Hope this helps! – m. simon borg Aug 15 '17 at 14:06
  • @m-simon-borg now if I import all object data into a view, say by using the (at)objects = Object.all in the Objects Controller, if I have thousands of object entries in my rails database, won't that try to load them all and slow down performance? Is there a best practice approach to limit the amount of data loading in that html tag? – JohnOHFS Aug 15 '17 at 18:32
  • @JohnOHFS yes, it will, but the major slowdown will not be rendering the data in the HTML tag but all the stuff you do with it after. It's best practice in any scenario to limit the data you're sending to the view to only the data that you need. Don't send all the records if you only need a few. This should be done in the controller by calling model scopes to narrow your queries, or by using Pagination to break up the index of records into smaller chunks (see kaminari gem) – m. simon borg Aug 15 '17 at 18:46
  • @m-simon-borg Got it. Thanks! – JohnOHFS Aug 15 '17 at 19:55