ViewComponents Cheatsheet

Useful ViewComponent cheatsheet. All available features on one page.

  • Generators

    • New

      rails generate component Example title content
      
    • Namespacing

      rails generate component Sections::Example title
      
    • Inline (without an template)

      rails generate component Example title --inline
      
  • Rendering

    • Multi-line block

      <%= render ExampleComponent.new do %>
      Content here
      <% end %>
      
    • Single-line block

      <%= render ExampleComponent.new { "Content here" } %>
      
    • with_content()

      <%= render ExampleComponent.new.with_content("Content here") %>
      
    • spacer_component

      <%= render(ExampleComponent.with_collection(@products, spacer_component: ExampleSpacerComponent.new)) %>
      
    • Conditional rendering

      def render? = true || false
      
  • Slots

    • renders_one

      renders_one :heading
      
    • renders_one Usage

      <%= render ExampleComponent.new do |component| %>
        <% component.with_heading { "Heading" } %>
      <% end %>
      
    • Default slot

      def default_header
        "Hello, World!"
      end
      
    • renders_many

      renders_many :articles
      
    • renders_many Usage

      <%= render ExampleComponent.new do |component| %>
        <% component.with_article do %>
          Article content here
        <% end %>
      <% end %>
      
    • Predicate method (renders_one)

      header?
      
    • Predicate method (renders_many)

      articles?
      
  • Helpers

    • View Helpers

      helpers.icon "home"
      
    • Use delegation

      delegate :icon, to: :helpers
      
    • Delegated usage

      icon "home"