Skip to content

How to make a component work with both 'new' and 'with_collection' #924

Answered by xkraty
AndreaBarghigiani asked this question in Q&A
Discussion options

You must be logged in to vote

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.
Chris

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@AndreaBarghigiani
Comment options

Answer selected by AndreaBarghigiani
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants