Skip to main content
  1. Home
  2. About ViewComponent

About ViewComponent

ViewComponent is a framework for Ruby on Rails that lets us build and share reusable components.

Compared to building the equivalent functionality using Rails’ partials and helpers, view components are:

  • easy to test as both the logic and rendered HTML can be examined individually
  • easier to understand than partials as they are backed by a Ruby object
  • incredibly efficient, up to 10 times faster than partials

They can be extended to provide custom JavaScript and CSS too, but this library doesn’t do this.


Some components contain elements that are repeated one or many times. For example, the header component can display multiple navigation items. These are implemented using ViewComponent’s Slot API.

Slots are view components that belong to other view components. For example, the table component has many rows and each row can have many cells.

Slots are called by opening a block when rendering the component and calling the slot by name against the object. In this example we have a shopping list with several items:

/ with arguments:
= render( ["Apple juice", "Bread", "Carrots"])

/ with slots:
= render( do |shopping_list|
  - shopping_list.item("Apple juice")
  - shopping_list.item("Bread")
  - shopping_list.item("Carrots")

Slots give us more flexibilty. In this scenario they’d make it easier to add logic to the list, or to add other arguments to each list item.

= render( do |shopping_list|
  - shopping_list.item(count: 3)
    | Apple juice

  - shopping_list.item("Bread", sliced: true)

  - if cupboard.carrots.count == 0
    - shopping_list.item("Carrots")