How to make a component work with both 'new' and 'with_collection' #924
-
Hi all and first of all sorry if this is a noob question but I have started to work with Rails a couple of months ago coming from a background as a PHP/WordPress developer mainly focused on the Frontend part. Also I have spent last year working only on React so my small knowledge of OOP is a bit rusty. I am not new to the web development world and I have to say that I really like the Rails ecosystem and have been really happy to see the ViewComponents and lucky me we use them even at work. So now that I presented myself, I thought it was necessary, let's get back to my issue. I have created a component that originally was used with <%= render MyComponent.new(title: "My title", content: 'My content') %> Then a colleague let me notice that in some situations we call the same component inside an # Instead of
<% my_data.each do |data| %>
<%= render MyComponent.new(title: data[:title], content: data[:content]) %>
<% end %>
# I did
<%= render MyComponent.with_collection(data) %> The problem arises when we need to use the same component with a single set of data that is not wrapped inside an Array, so here I am questioning the decision. I believe that So my question is: how should I approach this situation?
At least those are the ideas I came up with my knowledge of the field, do you have any suggestions or advice? Thank you in advance for the help. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hello @AndreaBarghigiani, components can be used both with_collection, both with single data just like that: class MyComponent < ViewComponent::Base
with_collection_parameter :data
def initialize(data:)
@data = data
end
end And you can render a single element like that @data = { title: 'Pizza Margherita', content: 'Tomato sauce, mozzarella' }
render MyComponent.new(data: @data) Or a collection @dataset = [
{ title: 'Pizza Margherita', content: 'Tomato sauce, mozzarella' },
{ title: 'Pizza Marinara', content: 'Tomato sauce, garlic, origan' }
]
render MyComponent.with_collection(@dataset) Hope that helps. |
Beta Was this translation helpful? Give feedback.
Hello @AndreaBarghigiani,
components can be used both with_collection, both with single data just like that:
And you can render a single element like that
Or a collection
Hope that helps.
Chris